Thread: How to use fwrite to copy a file to a file

  1. #1
    Registered User
    Join Date
    Feb 2013

    How to use fwrite to copy a file to a file

    this is what i've been thinking..

    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
    CA, USA
    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
    Where the sidewalk ends
    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, 07: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, 12:10 AM
  3. Replies: 2
    Last Post: 03-04-2010, 03:19 AM
  4. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 04:13 PM
  5. fwrite file size
    By lambs4 in forum C Programming
    Replies: 4
    Last Post: 04-04-2003, 04:49 PM
Website Security Test