c - fprintf 不工作

标签 c io

我正在测试 fprintf() 的用法,但它不起作用。当我第一次编写代码时,我忘记在 fprintf() 中添加 \n 并且它起作用了。但是,当我在“test 1 2”的开头添加 \n 时,它停止了工作。

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    FILE* f = fopen("test.txt", "r+");
    if( f == NULL) return 0;

    char str[4][10];

    for(int a = 0; a <= 3; ++a)
    {
        fscanf(f, " %[^\t\n]s", str[a]);
        printf("%s\n", str[a]);
    }

    fprintf(f, "\ntest 1 2\n");

    fclose(f);
    system("pause");
    return 0;
}

并且我的 test.txt 包含(而不是 \t\n 我按下了选项卡并输入了文件,但我无法在此处管理它)

a b\t c d\t e\n f g

最佳答案

For files open for appending (those which include a "+" sign), on which both input and output operations are allowed, the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a writing operation followed by a reading operation or a reading operation which did not reach the end-of-file followed by a writing operation.

Source

所以添加这个:

fflush(f);

在你的 fprintf 之前,如果你想追加到文件而不删除它以前的内容,或者这样:

rewind(f);

如果您想要覆盖内容,正如您的评论所指出的那样。

关于c - fprintf 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14364210/

相关文章:

c - C 中的管道 - 命令 2 中的错误

c - 如何使用 C 语言制作带有单个 .out 文件的 Mac 应用程序?

C - fopen() 的相对路径

java - 为什么我抛出 NullPointerException

io - 内存和 IO 带宽之间有什么区别,我们如何测量它们?

c - 使用 sprintf() 获得正确的格式

java - Java 二进制 I/O 问题

c++ - 为什么 std::sort 比手工编码的 "introsort"更快?

c - 参数不能为负(函数 : open)

c - 如何让 ANTLR3.5 在 C 中生成的解析器在 MVS EBCDIC 环境中工作?