读取并复制文件,中间有 EOF 指示器
我使用下面的代码从一个二进制文件复制到另一个二进制文件,但第一个文件包含一些 EOF 指示符 (0xFF) 作为其一部分,因此复制函数实际上复制文件直到其第一个 EOF 指示符。
例如:如果我的文件是 {0x01, 0x02, 0x03, 0xFF, 0x01, 0x02, 0xFF, 0xFF}
则只会复制 {0x01, 0x02, 0x03}
到新文件。知道如何修复它(或者也许我在那里遗漏了一些东西......)
代码:
int Util_Copy_File(char* source, char* dest)
{
FILE *fs,*ft;
char ch;
char infile[100];
sprintf(infile, "%s", dest);
fs = fopen(infile,"r");
if(fs==NULL)
{
return -1;
}
ft = fopen(dest,"w");
if(ft==NULL)
{
fclose(fs);
return STATUS_FAIL;
}
while(1)
{
ch = getc(fs);
if(ch==EOF)
{
break;
}
else
putc(ch,ft);
}
fclose(fs);
fclose(ft);
return 0;
}
谢谢, 本亚明
I used the code below to copy from one binary file to another, but the first file contains some EOF indicators (0xFF) as part of it, so the copy function actually copies the file until its first EOF indicator.
For example: if my file is {0x01, 0x02, 0x03, 0xFF, 0x01, 0x02, 0xFF, 0xFF}
then only {0x01, 0x02, 0x03}
will be copied to the new file. Any idea how to fix it (or maybe I'm missing something there...)
Code:
int Util_Copy_File(char* source, char* dest)
{
FILE *fs,*ft;
char ch;
char infile[100];
sprintf(infile, "%s", dest);
fs = fopen(infile,"r");
if(fs==NULL)
{
return -1;
}
ft = fopen(dest,"w");
if(ft==NULL)
{
fclose(fs);
return STATUS_FAIL;
}
while(1)
{
ch = getc(fs);
if(ch==EOF)
{
break;
}
else
putc(ch,ft);
}
fclose(fs);
fclose(ft);
return 0;
}
Thanks,
Binyamin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fgetc 返回 int,而不是 char ,因此您可以区分 EOF 和与 EOF 具有相同值的 char 之间的区别。
更改:
到
And (如果您使用 *nix,通常不相关)
到
fgetc returns an int, not a char , so you can tell the difference between EOF and a char with the same value as EOF.
Change:
to
And (usually not relevant if you're on *nix)
to
0xFF
不是EOF
。 -1 是EOF
。问题是您将getc
的int
返回值存储在char
中,这会将0xFF
折叠到-1(实际上它是实现定义的行为,但这就是常见实现所做的)。getc
的返回值是一个int
,其值在unsigned char
或EOF
范围内(其中值为-1)。二进制数据的正确类型是unsigned char
,而不是char
。0xFF
is notEOF
. -1 isEOF
. The problem is that you're storing theint
return value ofgetc
in achar
, which collapses0xFF
onto -1 (actually it's implementation-defined behavior but that's what common implementations will do).The return value of
getc
is anint
whose value is either in the range ofunsigned char
orEOF
(which has value -1). And the correct type for binary data isunsigned char
, notchar
.