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.