简单的程序,求指点为什么这里明明读到了文件结束之后还会多一次循环?
- C/C++ code
const char * file = "test.dat"; const char * fileout = "testout.dat"; ifstream fin; fin.open(file, ios_base::in |ios_base::binary); ofstream fout; streamoff i,j; if (fin.is_open()) { long n=0; char size[4]; while (! fin.eof() ) { fin.seekg(12, ios::cur); fin.read(size,4); n=*((long *)size); n=htonl (n); char *Buf=new char[n]; fin.read(Buf,n); fout.open(fileout,ios_base::out|ios_base::ate); j=fout.tellp(); fout.write(Buf,n); delete Buf; } } fin.close(); fout.close();求指点为什么这里明明读到了文件结束之后还会多一次循环?还有ios_base::ate模式为什么没有效果呢?
[解决办法]
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
whlie (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。