gpt4 book ai didi

c - 为什么我需要刷新我的 I/O 流以获得正确的结果?

转载 作者:太空狗 更新时间:2023-10-29 16:46:31 25 4
gpt4 key购买 nike

为什么下面的代码不起作用?我的意思是,它在控制台输出中显示了各种奇怪的字符。

#include <stdio.h>
char mybuffer[80];
int main()
{
FILE * pFile;
pFile = fopen ("example.txt","r+");
if (pFile == NULL) perror ("Error opening file");

else {
fputs ("test",pFile);

fgets (mybuffer,80,pFile);
puts (mybuffer);
fclose (pFile);
return 0;
}
}

但是,下面的代码运行良好。

#include <stdio.h>
char mybuffer[80];
int main()
{
FILE * pFile;
pFile = fopen ("example.txt","r+");
if (pFile == NULL) perror ("Error opening file");

else {
fputs ("test",pFile);
fflush (pFile);
fgets (mybuffer,80,pFile);
puts (mybuffer);
fclose (pFile);
return 0;
}
}

为什么我需要刷新流以获得正确的结果?

最佳答案

因为标准是这样说的 (§7.19.5.3/5):

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

这是有原因的:输出和输入通常是分开缓冲的。当出现刷新或查找时,它会将缓冲区与文件同步,否则会使它们不同步。这通常会提高性能(例如,当您进行读取时,它不必检查自从数据被读入缓冲区以来您正在读取的位置是否已被写入)。

关于c - 为什么我需要刷新我的 I/O 流以获得正确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2230636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com