Read write problem
I try to read from a file and to write to another file an arbitrary number of bytes
The first file is bigger than the number of bytes I read from it. Then I use a file compare utility to compare the files. The problem is that only the first 338 bytes are ok. After that I get an extra space(ASCII) offset and of course the rest of the file is diferent. No matter the size of buffer, I always get only the first 338 bytes correctly written.
int main (int argc, char* argv)
FILE * pFileR;
FILE * pFileW;
pFileR = fopen (argv, "rb");
strcpy (writeFileName, "new_");
strcat (writeFileName, argv);
pFileW = fopen (writeFileName, "w");
if (pFileR==NULL || pFileW==NULL)
fputs ("File error", stderr);
for(i=0; i<20; i++)
fread (buffer, 1, sizeof(buffer), pFileR);
fwrite (buffer, 1, sizeof(buffer), pFileW);
How big is the file?
You have to remember, on the last 32b chunk that it may not be 32b it could be say 29b (if there are 29b left in the "read" file. And you'll then write 29b + 3b (of rubbish) to the new file and they'll differ. Also if you run out of stuff to read after the first 10 calls, then you'll end up writing 32b of the 10th call (buffer) to the "write" file.
Check the return result of fread() and call fwrite() accordingly. Perhaps even control your loop in such a way that it's based on the fread() result so you stop reading when there is no more stuff to be read.
you open read file as binary and write file as text - you should use binary mode in both cases
Writing in text mode was the problem indeed. Now it's ok, the files are indentical as expected. Thanks vart.
I know I should check the number of bytes read and written. That's the way I wrote the code in the first place but then it gave me this error and I simplified the code in order to find the problem. The problem was that in text mode after 338 bytes a linefeed character was found that was exchanged with a linefeed + carriage return.
Problem solved, thank you all!