gpt4 book ai didi

c - C程序中输入输出之间的I/O

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:36 24 4
gpt4 key购买 nike

看到APUE的一段话(5.5章):

When a file is opened for reading and writing, the following restrictions apply:
(1) Output cannot be directly followed by input without an intervening fflush, fseek, fsetpos,or rewind.
(2) Input cannot be directly followed by output without an intervening fseek, fsetpos,or rewind, or an input operation that encounters an end of file.

我可以想象为什么我们要使用fseekfsetpos。但是为什么我应该在情况 (1) 中使用 fflush 而在情况 (2) 中使用 rewind
如果我们在情况 (1) 中使用 fflush,就没有什么可读的了。如果我们在情况 (2) 中使用倒带,则要输出的内容将与原始内容重叠。我对吗?

我已经尝试了 2 个实验:

int main() {
FILE *file_p = fopen("new.txt", "r+");
char buf[1024];
char *str;

fputs("hongkong\n", file_p);
fputs("shanghai\n", file_p);

fflush(file_p);

fputs(fgets(buf, 1024, file_p), stderr);

fclose(file_p);
return 0;
}
/* Segmentation fault */

int main() {
FILE *file_p = fopen("new.txt", "r+");
char buf[1024];
char *str;

fgets(buf, 1024, file_p);
rewind(file_p);
fputs("hongkong\n", file_p);

fclose(file_p);
return 0;
}
/* origin text in new.txt is:
shanghai
taipei
after execution:
hongkong
taipei
*/

我对这一段有什么误解吗?

最佳答案

1) 将数据写入文件时,它不会直接进入文件,而是进入缓冲区。当它最终被填满时,它会留下写入的文件。这一切都是为了提高性能。 fflush() 的用途之一是将缓冲区中的数据保存到文件中,而不管该缓冲区是否已填满一半。这就像数据库的提交。出于这个原因,如果你想读取一个文件,在你需要确保所有数据都存在之前。

2) 提醒要获取文件存在一个沿着文件移动的光标。如果你往文件中写入一个数据寄存器,光标会在文件的最后一个位置(或者你之前所在的位置+1),所以如果你在那之后读取它,你会到达EOF(以防万一你在最后一次登记)。

在你的第一个例子中:

 fputs(fgets(buf, 1024, file_p), stderr);

fgets() 到达 EOF,因此 fputs() 给您带来段错误,因为它正在接收 NULL。

在第二个中你覆盖了第一行。

关于c - C程序中输入输出之间的I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24903442/

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