Reputation: 1690
I have a little confused about the result of two slightly different piece of code like this:
FILE* file=fopen("test.txt","w");
char buffer[6]="hello";
char arr[6]="haloo";
//setbuf(file,buffer);
fputs(arr,file);
//fflush(file);
As you can see I firstly commented out two line of code. So the buffer would not be flushed until I close the program, at which time the file stream will be closed too. And then, as what I expect, the program would write the haloo
to the test.txt
as soon as I close the program. And the same things happened When I don't commented out those two lines. Like this:
setbuf(file,buffer);
fputs(arr,file);
fflush(file);
But, when I only commented out only the flush(file)
line of code, like this:
setbuf(file,buffer);
fputs(arr,file);
//fflushed(file);
strange thing happen. I got things like 2800 c579 7a
in my test.txt
when I close my program.
And then I try to change the buffer a little bit, to something like this:
char buffer[5]="hell"; //change the contents a little bit
char arr[5]="halo"; // also change a little bit
setbuf(file,buffer);
fputs(arr,file);
//fflush(file);
Then I got 00c5 797a
in my text.txt
.
So I wonder if this is any undefined behavior or default pattern that I don't know.
Upvotes: 1
Views: 66
Reputation: 347
I think you want to terminate your buffer with a '\0'. Check that out.
If you are not calling fclose, there might be an undefined behaviour problem because of setbuf, see http://man7.org/linux/man-pages/man3/setbuf.3.html.
Check adding a fclose at the end of the program, this will make sure the fflush is enforced and the stream is cleanly closed, while at the same time avoiding the above mentioned bug.
Upvotes: 1