【发布时间】:2015-12-29 16:30:06
【问题描述】:
我正在尝试从文件“file.txt”中读取内容并将其中的每个字符写入“copy.txt”,但在“copy.txt”文件的末尾出现了一个奇怪的字符。
我正在尝试打开和关闭这两个文件,并在程序中修改 while 循环的主体,以便不再将字符放入标准输出(stdout)。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
FILE *from, *to;
from = fopen("file.txt", "r");
if (from == NULL)
{
perror("file.txt doesn't exist.");
exit(1);
}
to = fopen("copy.txt", "w");
if (to == NULL)
{
perror("copy.txt doesn't exist.");
exit(1);
}
do
{
c = getc(from);
putc(c, to);
}
while(c != EOF);
fclose(to);
fclose(from);
exit(0);
}
【问题讨论】:
-
在
getc()返回EOF之后,您使用EOF结果调用putc()。 -
另外,
c应该是int,而不是char。 -
顺便说一下@JamesR,使用
int c而不是char c的原因是EOF不一定可以在char中表示。 -
你可以把循环改成
while ((c = getc(from)) != EOF) { putc(c, to); }。 -
请一致地缩进代码。建议在每个左大括号 '{' 后缩进 4 个空格,并在每个右大括号 '}' 之前不缩进。不要使用制表符进行缩进,因为每个文字处理器/编辑器都以不同的方式定义制表位/制表符宽度。使用 4 个空格,因为即使使用可变宽度字体也是如此。
标签: c file input while-loop