怎样判断文件结尾

来源:百度知道 编辑:UC知道 时间:2024/06/25 02:32:27
实现dos的内部命令copy,要判断文件结尾.
请不要说用EOF,因为目标文件很可能不是一个文本文件.还试了下用feof也不行.那么有什么别的办法呢?
下面是有bug的源代码,核心代码是while( (ch=fgetc(srcFile))!=EOF) fputc(ch,destFile);其他部分仅对一些输入和文件异常做了处理.

#include <iostream>
int main(int argc,char* argv[])
{
FILE* srcFile=NULL,*destFile=NULL;
int ch=0;
if(argc!=3)
{
printf("格式:%s src-file-name dest-file-name\n",argv[0]);
}
else
{
if( (srcFile=fopen(argv[1],"r"))==NULL)
{
printf("源文件%s打开失败\n",argv[1]);
}
else
{
if( (destFile=fopen(argv[2],"w"))==NULL)
{
printf("目标文件%s打开失败\n",argv[2]);
fclose(srcFile);
}
else
{
while( (ch=fgetc(srcFile))!=EOF) fputc(ch,destFile);
// while (!feof(srcFile))
// {
// ch=fgetc(srcFile);
// fputc(ch,destFile);
// }
printf("拷贝成功");

1. if( (srcFile=fopen(argv[1],"r"))==NULL)
2. if( (destFile=fopen(argv[2],"w"))==NULL)
打开和写入文件都要使用二进制格式:"rb"|"wb"

3. while( (ch=fgetc(srcFile))!=EOF) fputc(ch,destFile);
使用fread(...)和fwrite(...),然后用feof(...)和fwrite(...)的返回值来判断是否结束.

4. #include <iostream>
下面全是c代码,却包含个c++头,而且没有引入std.
如果使用c++,使用ifstream::read(...)和ofstream::write(...),打开时加入ios::binary.使用ifstream::eof()或者ifstream::fail()来判断是否读入结束.

以上在每次读入的时候都要先进行EOF判断,否则将2次写入最后读取的内容.

尝试将
(ch=fgetc(srcFile))!=EOF
改为
fscanf(srcFile,"%c",&ch)>0