简体   繁体   English

流缓冲区中的默认内容

[英]the default contents in the buffer of a stream

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. 然后,按照我的期望,程序将在我关闭程序后立即将haloo写入test.txt 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: 但是,当我仅注释掉flush(file)代码行时,如下所示:

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. 当我关闭程序时,在test.txt出现了2800 c579 7a

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 . 然后我的text.txt00c5 797a

So I wonder if this is any undefined behavior or default pattern that I don't know. 所以我想知道这是否是我不知道的任何未定义行为或默认模式。

I think you want to terminate your buffer with a '\\0'. 我认为您想以'\\ 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 . 如果不调用fclose,则可能是由于setbuf引起的不确定行为问题,请参见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. 检查在程序末尾添加一个fclose,这将确保强制执行fflush并完全关闭流,同时避免上述bug。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM