How to use fwrite to copy a file to a file

This is a discussion on How to use fwrite to copy a file to a file within the C Programming forums, part of the General Programming Boards category; this is what i've been thinking.. Code: char buffer[256]; FILE *fp; FILE *fw; fp = fopen("read.txt", "r"); fw = fopen("write.txt", ...

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    33

    How to use fwrite to copy a file to a file

    this is what i've been thinking..

    Code:
    char buffer[256];
    FILE *fp;
    FILE *fw;
    
    fp = fopen("read.txt", "r");
    fw = fopen("write.txt", "w");
    
    //not sure in this part.. 
    while ((fgets(buffer,256,fw))!= NULL) 
        {
            fwrite(buffer, 256, fw);
        }

  2. #2
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Posts
    326
    Why not compile it and try it yourself?

    1) Don't mix fgets and fwrite. Either use fread/fwrite or fgets/fputs. One operates on null-terminated strings, the other operates on bytes. In this case, since you're just copying bytes around, use fread/fwrite.
    2) You're reading and writing on the same file.
    3) Open your files as binary; this makes a difference on some OS like Windows.
    4) fread and fwrite return meaningful values; they don't always write or read the requested no. of bytes, so you have to account for this as well.

  3. #3
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    In addition to using the wrong function for reading, you are also attempting to read and write to the same fie.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-13-2013, 08:10 PM
  2. fwrite function to write png file stream into a file
    By mdivya in forum C Programming
    Replies: 2
    Last Post: 08-26-2011, 01:10 AM
  3. Replies: 2
    Last Post: 03-04-2010, 04:19 AM
  4. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 05:13 PM
  5. fwrite file size
    By lambs4 in forum C Programming
    Replies: 4
    Last Post: 04-04-2003, 05:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21