![](/img/trans.png)
[英]C language / How to read input from one file and write an output to another file
[英]Read input from one file and write it to another file in C
我正在尝试从文件“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);
}
你的问题在于这个循环:
do
{
c = getc(from);
putc(c, to);
}
while(c != EOF);
您需要了解的是do-while
和while
循环之间的区别。 while
循环将在运行循环之前评估表达式(因此循环运行至少0次)并且do-while
循环do-while
循环循环之后评估(因此运行至少一次)。
所以有什么问题? 你读了一个字符,把它copy.txt
,然后评估它的EOF
是否退出循环。 现在,从文件中读取最后一个字符时会发生什么? 循环将再次运行,因为最后一个字符不是EOF
。 您的程序将再读一个字符并写入该文件。 这就是你的意思。
因此,为了解决问题,您需要在编写之前评估EOF
。 这是两次尝试,一次将保持你的do-while
循环,另一次使用while
循环(更清晰):
Do-While Attempt(不漂亮且不必要的话):
do
{
c = getc(from);
if (c != EOF) {
putc(c, to);
}
}
while(c != EOF);
尝试时:
while ((c = getc(from)) != EOF) {
putc(c, to);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.