c - 为什么 fflush 不允许我的程序切换模式?
问题描述
我有以下 C 应用程序:
#include <stdio.h>
int main() {
// Create a file.
FILE *filePointer = fopen("deleteme.txt", "w+");
if (filePointer == NULL) {
printf("Operation failed.\n");
return 0;
}
// Write "Test" to the file.
if (fputs("Test", filePointer) == EOF) {
printf("Operation failed.\n");
return 0;
}
// Seek to the beginning.
if (fseek(filePointer, 0, SEEK_SET) != 0) {
printf("Operation failed.\n");
return 0;
}
// Read the character "T".
if (fgetc(filePointer) == EOF) {
printf("Operation failed.\n");
return 0;
}
// Flush streams.
fflush(filePointer);
// Write "esting" to the file.
if (fputs("esting", filePointer) == EOF) { // <--- Fails here.
printf("Operation failed.\n");
return 0;
}
printf("Operation succeeded.\n");
return 0;
}
我在 Windows 操作系统下运行它:
- 视觉工作室代码 1.48.2
- C/C++(Visual Studio 代码扩展)0.29.0
- Code Runner(Visual Studio Code 的扩展)0.11.0
- MinGW(mingw32-base)2013072200
我上面链接的代码在调用fputs("esting", filePointer)
. 这是为什么?在线查看文档,它说:
在为更新而打开的文件中(即为读取和写入而打开),流应在输出操作之后刷新,然后再执行输入操作。这可以通过重新定位(fseek、fsetpos、rewind)或显式调用 fflush 来完成
正如您在上面的代码中看到的那样,由于我已经在更新模式下打开了文件w+
,所以我在调用fflush
之前显式调用fputs
。我希望这可以让我切换模式,以便我可以在阅读后执行写入,还是我误解了文档?我知道如果我fflush
用调用替换上面的代码将起作用fseek
(交换似乎可以解决这个问题),但是为什么它在使用时不起作用?fflush
fseek(filePointer, 0, SEEK_CUR)
fflush
解决方案
推荐阅读
- python - 我如何将输出变成表格?
- spring-boot - 从 Maven 启动多个 Spring Boot 应用程序
- angular - 以角度 6 显示对象数组的自动完成选项
- javascript - 如何动画 svg 路径填充 javascript 而不是 HTML
- biztalk - Web 服务接口的 BizTalk 实现
- javascript - 将一个数组中的每个值与另一个数组中的每个值组合
- css - 带有边缘的可扩展剪辑路径多边形
- python - 如何在 SALib 中为 Delta Moment-Independent Measure delta.analyze 选择 num_resamples?
- android - image_picker 在 android 中选择图像和应用程序崩溃
- flutter - Flutter:使ListView在底部反弹并在顶部位置夹住