[英]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.