fprintf中不工作 [英] fprintf not working
问题描述
我测试的使用fprintf中()
,这是行不通的。当我第一次写了code我忘了补充 \\ n
在 fprintf中()
和它的工作。然而,当我加入 \\ n
在测试1 2,它停止工作。开始
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释的main()
{
FILE * F =的fopen(test.txt的,R +);
如果(F == NULL)返回0; 炭海峡[4] [10]; 对于(int类型的= 0; A< = 3; ++一)
{
的fscanf(F,%[^ \\ t \\ n]的,海峡[A]);
的printf(%S \\ n,海峡[A]);
} fprintf中(F,\\ NTEST 1 2 \\ n); FCLOSE(F);
系统(暂停);
返回0;
}
和我的test.txt包含(而不是 \\ t
和 \\ n
I pressed选项卡,在该文件中进入,但我不能在这里进行管理)
A B \\ t C D \\ T E \\ n
F G
块引用>解决方案
有关打开文件进行追加(那些包含一个+号),对
其中两个输入和输出操作是允许的,该流应
被刷新(fflush)之间或重新定位(fseek的,fsetpos,倒带)
任一随后的读出操作或写入操作
读出操作而没有达到结束文件后跟
写操作。
块引用>所以补充一点:
fflush(F);
在你的
fprintf中
如果要附加到文件而不删除其previous内容,或者这样的:退(F);
如果您想覆盖的内容,通过您的评论指出作为
I'm testing the usage of
fprintf()
and it is not working. When I first wrote the code I forgot to add\n
insidefprintf()
and it worked. However, when I added\n
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, " %[^\t\n]s", str[a]); printf("%s\n", str[a]); } fprintf(f, "\ntest 1 2\n"); fclose(f); system("pause"); return 0; }
and my test.txt contains ( instead of
\t
and\n
I pressed tab and enter in the file but I couldn't manage it here)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.
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屋!