alf
alf

Reputation: 681

printf prints to a binary file in c

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

Upvotes: 0

Views: 2230

Answers (1)

hmjd
hmjd

Reputation: 122001

The calls to fwrite() are incorrect as they are instructing fwrite() to write 10 characters 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:

fwrite("test", 1, 4, out);

As per comment, if there must be 10 characters then declare an array:

char msg[10] = "test"; /* Unspecified elements will be null. */

fwrite(msg, 1, sizeof(msg), out);

Upvotes: 3

Related Questions