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.
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.
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);