在c中复制.exe文件和文本文件的区别
我编写了以下代码将文本文件复制到另一个文件:
FILE *fpr, *fpw;
int ch;
fpr = fopen("M.txt","r");
fpw = fopen("P.txt","w");
if(fpr == NULL)
printf("File open failed!");
else
{
while(1)
{
ch = fgetc(fpr);
if(ch == EOF)
break;
fputc(ch, fpw);
}
fclose(fpr);
fclose(fpw);
printf("Successfully copied!");
}
它工作得很好。然后我将 int ch
更改为 char ch
它也对我有用。但是,当我使用以下代码复制 .exe 文件时,文件复制无法正常工作。
FILE *fpr, *fpw;
char ch;
fpr = fopen("M.exe","rb");
fpw = fopen("P.exe","wb");
if(fpr == NULL)
printf("File open failed!");
else
{
while(1)
{
ch = fgetc(fpr);
if(ch == EOF)
break;
fputc(ch, fpw);
}
fclose(fpr);
fclose(fpw);
printf("Successfully copied!");
}
我将 char ch
更改为 int ch
然后它工作正常!为什么二进制文件而不是文本文件会发生这种情况?在二进制情况下使用 char ch
会发生什么? 请帮忙... 感谢您提前反馈。
I wrote the following code to copy the text file to another:
FILE *fpr, *fpw;
int ch;
fpr = fopen("M.txt","r");
fpw = fopen("P.txt","w");
if(fpr == NULL)
printf("File open failed!");
else
{
while(1)
{
ch = fgetc(fpr);
if(ch == EOF)
break;
fputc(ch, fpw);
}
fclose(fpr);
fclose(fpw);
printf("Successfully copied!");
}
It worked perfectly. Then I changed int ch
to char ch
it also worked for me. But when i used the following code for copying a .exe file, file copying is not working correctly.
FILE *fpr, *fpw;
char ch;
fpr = fopen("M.exe","rb");
fpw = fopen("P.exe","wb");
if(fpr == NULL)
printf("File open failed!");
else
{
while(1)
{
ch = fgetc(fpr);
if(ch == EOF)
break;
fputc(ch, fpw);
}
fclose(fpr);
fclose(fpw);
printf("Successfully copied!");
}
I changed char ch
to int ch
then it's working fine! Why this happens with binary files not with text file? What happens when char ch
was used in the case of binary?
Please help...
Thank you for your feed back in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为 char 的 EOF 可能是 0 或 255,它可以显示在二进制文件的中间,但不能显示在文本文件中(这就是为什么只有文本文件适用于 char)。然而,对于 int 来说 EOF 是 -1,无论如何它都不能出现在文件中间(只有 0-255 可以)。
It's because EOF is probably 0 or 255 for char which can show up in middle of binary file but can't in text file(that's why only text file work for char). However EOF is -1 for int which can't show up in middle of a file no matter what(only 0-255 inclusive can).
由于
fgetc()
可以返回与任何字符对应的整数加上不同的值 EOF,因此您无法将其结果存储在char
中,然后可靠地测试 EOF。您必须像最初一样使用int
。Since
fgetc()
can return the integer corresponding to any character plus a distinct value EOF, you cannot store its result in achar
and then test for EOF reliably. You must use anint
as you did originally.fgetc()
和fputc()
设计用于处理文本数据,而不是二进制数据。请改用fread()
和fwrite()
。fgetc()
andfputc()
are designed for handling textual data, not binary data. Usefread()
andfwrite()
instead.