【发布时间】:2012-03-22 07:05:51
【问题描述】:
我有一个如下所示的程序。对于它,我有几个问题:
1)。 为什么它在不同平台上会产生不同的结果?我稍后会粘贴屏幕截图。
2)。 我正在使用 fail() 方法来检查“file.read()”是否失败。这是正确的吗?我使用 fail() 方法是因为 this web page 是这样说的:
如果设置了failbit 或badbit,则该函数返回true。如果在输入操作期间发生除了到达文件结尾之外的错误,则至少设置这些标志中的一个。
但后来我读到了这个关于 istream::read() here 的页面。它说 eofbit 和 failbit 将始终同时设置.. 这是否意味着正常的 EOF 情况也会导致 fail() 返回 true?这似乎与“除了到达文件结束之外”发生冲突..
谁能帮我澄清我应该如何使用这些方法?我应该改用 bad() 吗?
我的程序
#include <iostream>
#include <fstream>
using namespace std;
#ifdef WIN32
char * path="C:\\Workspace\\test_file.txt";
#else
char * path="/home/robin/Desktop/temp/test_file.txt";
#endif
int main(int argc, char * argv[])
{
ifstream file;
file.open(path);
if (file.fail())
{
cout << "File open failed!" << endl;
return -1; // If the file open fails, quit!
}
// Calculate the total length of the file so I can allocate a buffer
file.seekg(0, std::ios::end);
size_t fileLen = file.tellg();
cout << "File length: " << fileLen << endl;
file.seekg(0, std::ios::beg);
// Now allocate the buffer
char * fileBuf = new (std::nothrow) char[fileLen+1];
if (NULL == fileBuf)
return -1;
::memset((void *)fileBuf, 0, fileLen+1); // Zero the buffer
// Read the file into the buffer
file.read(fileBuf, fileLen);
cout << "eof: " << file.eof() << endl
<< "fail: " << file.fail() << endl
<< "bad: " << file.bad() << endl;
if (file.fail())
{
cout << "File read failed!" << endl;
delete [] fileBuf;
return -1;
}
// Close the file
file.close();
// Release the buffer
delete [] fileBuf;
return 0;
}
test_file.txt 内容(用“vim -b”显示。这是一个非常简单的文件):
Windows 上的结果(Visual Studio 2008 SP1):
Linux 上的结果(gcc 4.1.2):
【问题讨论】:
-
cplusplus.com 不是一个好的参考。它充满了不好的例子(比如测试不应该的流
fail()成员)和事实错误。我推荐en.cppreference.com。 -
尝试以二进制模式打开文件。