我正在测试操作文件的基本功能。
我尝试先打开/关闭一个文件来创建它,然后再次打开/关闭它来附加到它。最后,我打印出文件中的内容。
我的代码当前如下所示:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char mark;
/* WRITING: */
file= fopen("goodbye.c","w");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
printf("Enter data to write to .c file:");
while((mark= getchar())!=EOF)
{
putc(mark,file);
}
fclose(file);
/* APPENDING: */
file= fopen("goodbye.c","a");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
char add;
scanf("%c",add);
putc(add,file);
fclose(file);
/* READING: */
file= fopen("goodbye.c","r");
if(!file)
{ printf("Couldn't open file.\n");
exit(EXIT_FAILURE); }
while((mark= getc(file))!= EOF)
{
printf("%c",mark);
}
fclose(file);
}
有了这个,我无法追加到文件中。当使用getchar()时,我首先在完成写操作后键入ctrl+d。在这之后,它继续打印出我刚刚写的内容,而不是给我附加到文件中的机会。ctrl+d是否以某种方式中断了scanf?
如何得到我想要的结果?
最佳答案
代码只允许在文件中附加一个字符,这有点小气。如果文本文件的最后一行没有以换行符结尾(如果添加了换行符以外的内容,则不会以换行符结尾),它也可能(至少在理论上)导致某些系统出现问题。也许你需要一个循环来读取多个字符?
此外,由于在EOF之前不停止初始输入,因此需要清除stdin
和clearerr(stdin)
上的“错误”,以便进行进一步输入。这在Mac OS X 10.10.1 Yosemite上正常工作;在其他Unix系统上也应该如此。我不能自信地回答基于Windows的代码,除非它使用Cygwin之类的东西来模拟Unix,但我希望它在那里也能以同样的方式工作,即使使用MSVC。
顺便说一下,我的编译器抱怨在调用&
时缺少scanf()
,地址是:
char add;
scanf("%c",add);
如果你的编译器没有抱怨,要么提高警告级别,要么找一个更好的编译器。
这段代码的工作原理与我所期望的一样:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file;
char mark;
/* WRITING: */
file = fopen("goodbye.c", "w");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
printf("Enter data to write to .c file:");
while ((mark = getchar()) != EOF)
{
putc(mark, file);
}
fclose(file);
printf("EOF 1\n");
/* APPENDING: */
file = fopen("goodbye.c", "a");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
clearerr(stdin);
char add;
while (scanf("%c", &add) == 1)
putc(add, file);
fclose(file);
printf("EOF 2\n");
/* READING: */
file = fopen("goodbye.c", "r");
if (!file)
{
printf("Couldn't open file.\n");
exit(EXIT_FAILURE);
}
while ((mark = getc(file)) != EOF)
{
printf("%c", mark);
}
fclose(file);
return 0;
}
唯一实质性的改变是在循环周围添加一个循环——尽管坦白说,最好还是在第一个输入循环中使用cc,比如将调用固定到
scanf()
,添加两个在检测到EOF时报告的语句,并允许输入继续。样本输出
不带
getchar()
的代码:Enter data to write to .c file:Happiness is a bug-free program.
Happiness is seldom attained.
EOF 1
EOF 2
Happiness is a bug-free program.
Happiness is seldom attained.
用
scanf()
编码:Enter data to write to .c file:Happiness is a bug-free program.
Happiness is seldom attained.
EOF 1
But it helps when you add the clearerr(stdin) to this one.
EOF 2
Happiness is a bug-free program.
Happiness is seldom attained.
But it helps when you add the clearerr(stdin) to this one.
关于c - C写入后追加到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27117973/