fprintf 不工作 [英] fprintf not working
问题描述
我正在测试 fprintf()
的用法,但它不起作用.当我第一次编写代码时,我忘记在 fprintf()
中添加
并且它起作用了.但是,当我在test 1 2"开始时添加
时,它停止工作.
#include #include int主(){FILE* f = fopen("test.txt", "r+");if( f == NULL) 返回 0;字符 str[4][10];for(int a = 0; a <= 3; ++a){fscanf(f, " %[^
]s", str[a]);printf("%s
", str[a]);}fprintf(f, "
test 1 2
");fclose(f);系统(暂停");返回0;}
并且我的 test.txt 包含(而不是
和
我按 Tab 键并输入文件,但我无法在这里管理它)><块引用>
a b c d e fg
对于为追加而打开的文件(包含+"号的文件),在允许输入和输出操作,流应该被刷新 (fflush) 或重新定位 (fseek, fsetpos, rewind)要么是写操作,然后是读操作,要么是未到达文件末尾的读取操作后跟写操作.
所以添加这个:
fflush(f);
在你的 fprintf
之前,如果你想附加到文件而不删除它以前的内容,或者这个:
rewind(f);
如果你想覆盖你评论中指出的内容.
I'm testing the usage of fprintf()
and it is not working. When I first wrote the code I forgot to add
inside fprintf()
and it worked. However, when I added
at the start of "test 1 2" it stopped working.
#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, " %[^
]s", str[a]);
printf("%s
", str[a]);
}
fprintf(f, "
test 1 2
");
fclose(f);
system("pause");
return 0;
}
and my test.txt contains ( instead of
and
I pressed tab and enter in the file but I couldn't manage it here)
a b c d e 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.
So add this:
fflush(f);
before your fprintf
if you want to append to the file without deleting its previous contents, or this:
rewind(f);
if you want to overwrite the content, as pointed by your comment.
这篇关于fprintf 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!