- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
为什么下面的代码不起作用?我的意思是,它在控制台输出中显示了各种奇怪的字符。
#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/
我是一名优秀的程序员,十分优秀!