流缓冲区中的默认内容

the default contents in the buffer of a stream

我对这样两段略有不同的代码的结果有点困惑:

FILE* file=fopen("test.txt","w");
char buffer[6]="hello";
char arr[6]="haloo";

//setbuf(file,buffer);
fputs(arr,file);
//fflush(file);

如你所见,我首先注释掉了两行代码。所以在我关闭程序之前缓冲区不会被刷新,此时文件流也将被关闭。然后,如我所料,程序会在我关闭程序后立即将 haloo 写入 test.txt。当我不注释掉这两行时,同样的事情发生了。像这样:

setbuf(file,buffer);
fputs(arr,file);
fflush(file);

但是,当我只注释掉 flush(file) 行代码时,像这样:

setbuf(file,buffer);
fputs(arr,file);
//fflushed(file);

奇怪的事情发生了。当我关闭我的程序时,我的 test.txt 中出现了类似 2800 c579 7a 的东西。

然后我尝试将缓冲区稍微更改为如下所示:

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

然后我在 text.txt 中得到了 00c5 797a

所以我想知道这是否是我不知道的任何未定义行为或默认模式。

我想你想用'\0'来终止你的缓冲区。检查一下。

如果您不调用 fclose,可能会因为 setbuf 而出现未定义的行为问题,请参阅 http://man7.org/linux/man-pages/man3/setbuf.3.html

检查在程序末尾添加一个 fclose,这将确保执行 fflush 并干净地关闭流,同时避免上述错误。