fread and fwrite.. extra data being written to file

hi all,

I've been trying to write a simple C program to use fread and fwrite to read some data from a file and write it into another file. It works, though i always seem to get some extra text at the end. Usually part of the original text. Heres my code. Any help is much appreciated.

thanks,
ben

**************************************************
#include <stdio.h>

int main( void)
{
unsigned char *buff;
FILE *fptr;
FILE *fptr2;

if (( fptr = fopen("file.txt", "rb" )) == NULL || (fptr2 = fopen("file2.txt", "wb")) == NULL){
printf( "File could not be opened.\n");
}

else {
while ( !feof(fptr)){

fread (buff , 1 , sizeof(buff) , fptr );
fwrite (buff , 1 , sizeof(buff) , fptr2 );


}
fclose(fptr);
fclose(fptr2);
}
}

It is because you are looping on eof. feof() will return true after the last fread() doesn't work. For example:

File:
abc

If you use your code with this file, you will get an 'a', a 'b', and a 'c', but the eof is still not reached until you attempt to read again, and since the buffer is not modified, you will write an extra 'c' to the output file.
thanks firedraco,

I used the file "abc" and it returned an extra "abc" on the next line. how do i modify the buffer?
The fread() function returns the number of items it read. You should be looping against that, and not using feof() at all.

Why doesn't anyone ever use code tags?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        while (1) {
            /* Read as many bytes as we can from the file.   *
             * Keep track of how many bytes we actually got. */
            size_t readcount = fread(buff, 1, sizeof(buff), fptr);

            /* If there weren't any more bytes to read, then we are done. */
            if (!readcount) break;

            /* Otherwise, write the bytes back out to the output file. */
            fwrite(buff, 1, readcount, fptr2);
        }

        /* At this point, all bytes from the input file have been copied to the output file. */
        fclose(fptr);
        fclose(fptr2);

Hope this helps.
Topic archived. No new replies allowed.