|
| benjammin (2) | |
| 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); } } | |
| firedraco (2048) | |
| 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. | |
| benjammin (2) | |
| thanks firedraco, I used the file "abc" and it returned an extra "abc" on the next line. how do i modify the buffer? | |
| Duoas (2964) | |||
| 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?
Hope this helps. | |||
Registered users can post in this forum.
