C中不同的输出内容文件副本 [英] Different output content file copy in C
问题描述
你好,我在C语言中有一个简单的复制文件程序,但是当我使用第二种方法时,我无法解释为什么我在目标文件中得到了不同的输出. for循环的正确输出:
Hello i had a simple copy file program in C but i cant explain why i get different output in the destination file when i use the 2nd method. The correct output with for loop:
I am the worst programmer in the world!
:D
And this is bla bla bla bla
more bla bla bla...
使用while循环但在EOF中会生成随机字符的
BUT with while loop a random char is generated in EOF:
I am the worst programmer in the world!
:D
And this is bla bla bla bla
more bla bla bla...
代码是
int main()
{
int i;
char ch;
create_files();
FILE *src = fopen("best.txt", "r");
FILE *dst = fopen("copied.txt", "w");
for(i=getc(src); i!=EOF; i=getc(src)) //correct copy
{
putc(i, dst);
}
/* while(!feof(src)) //woot?
{
ch=fgetc(src);
fputc(ch,dst);
}*/
fclose(dst);
fclose(src);
return 0;
}
void create_files()
{
FILE *fp;
fp = fopen("best.txt","w");
fprintf(fp,"I am the worst programmer in the world!\n:D\n And this is bla bla bla bla\n more bla bla bla...\n");
fclose(fp);
}
我已经使用了fputc或putc以及fgetc或getc,并且仍然相同.我忘了什么吗?
i ve used both fputc or putc and fgetc or getc and still the same. Did i forget something?
推荐答案
什么
while (!feof(src)) {
ch=fgetc(src);
fputc(ch,dst);
}
确实是:
- 检查EOF
- 读取字符,可能导致EOF
- 输出刚刚读取的字符,而不检查EOF.
当发生EOF时,在下一次迭代中的(1)检入之前,仍将执行(3).特殊值EOF
转换为char
并输出.
When EOF occurs, (3) is still executed before the check in (1) in the next iteration. The special value EOF
is converted to a char
and output.
正确的循环是
while ((ch = fgetc(src)) != EOF)
fputc(ch, dst);
假设,您将ch
的类型指定为int
,因为char
不能表示EOF
.注意支票中的分配;一些程序员会告诉您这很丑陋,但是使用它的人太多了,您可能还不习惯.您的变体for
循环也是正确的.
assuming you give ch
the type int
, because a char
cannot represent EOF
. Note the assignment within the check; some programmers will tell you that's ugly, but so many use it that you might as well get used to it. Your variant for
loop is correct as well.
(除了1:fputc
等同于putc
,fgetc
等同于getc
,只要您不尝试在函数指针上下文中使用它们即可.)
(Aside 1: fputc
is equivalent to putc
and fgetc
to getc
, as long as you don't try to use them in a function pointer context.)
(除了2:您的while
循环也不会检查流错误,而检查EOF
也会返回捕获的错误.)
(Aside 2: your while
loop also doesn't check for stream errors, while checking for EOF
returns catches that as well.)
这篇关于C中不同的输出内容文件副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!