我正在测试 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.
所以添加这个:
fflush(f);
在你的 fprintf
之前,如果你想追加到文件而不删除它以前的内容,或者这样:
rewind(f);
如果您想要覆盖内容,正如您的评论所指出的那样。
关于c - fprintf 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14364210/