I have a binary file that I open, modify, and close. And then I printf to the console.
This all works fine, but I realized just now that it’s appending whatever I’m printing to the console to the end of the binary file, and it makes no difference whether or not the file is open or closed.
The same thing happens with fprintf.
What’s going on here? Is there something I don’t understand about file I/O?
Update: Here’s the code:
FILE *out = fopen("test","wb+");
fseek(out,0,SEEK_END);
fwrite("test",1,10,out);
fwrite("test",1,10,out);
fwrite("test",1,10,out);
int pos = ftell(out);
fwrite(&pos,sizeof(int),1,out);
fclose(out);
fprintf(stdout,"%s","hello");
The calls to
fwrite()are incorrect as they are instructingfwrite()to write10characters from a 5 character array (string literals have an implicit null character appended). This will be accessing beyond the ends of the array, resulting in undefined behaviour and is a probable cause of the strange behaviour.Correct the
fwrite()calls:As per comment, if there must be 10 characters then declare an array: