我有一个程序,如下所示。为此,我有几个问题:
1)。 为什么在不同的平台上会产生不同的结果? 我稍后将粘贴屏幕截图。
2)。 我正在使用fail()方法检查“file.read()”是否失败。这样对吗? 我使用了fail()方法,因为this web page这样说:
但是稍后,我阅读了有关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)上的结果:
最佳答案
我建议使用没有错误的引用。
http://en.cppreference.com/w/cpp/io/basic_ios/fail说:
C++标准说:
没有“文件结束以外”的东西。尝试读取文件末尾的操作也将导致设置failbit
。 eofbit
仅用于将特定的失败原因与其他原因区分开(并且起初没有想到的有用)。
您应该简单地测试到bool
的转换。
if(file) { // file is not in an error state
它是
!fail()
的同义词,但是它更有用,因为您可以使用它来直接测试读取操作的结果,而无需额外的括号(像!(stream >> x).fail()
这样的东西会很尴尬):if(file.read(fileBuf, fileLen)) { // read succeeded
您会注意到,对流的所有读取操作都会返回流本身,这使您可以执行此操作。
您在Windows和Linux之间看到的差异是因为文件以文本模式打开:换行符将由实现以静默方式转换。这意味着将
"\r\n"
组合(在Windows中用于换行符)将转换为Windows中的单个'\n'
字符,从而使文件只有8个字符。注意vim在第一行的末尾如何显示^M
:这是'\r'
的一部分。在Linux中,换行符只是'\n'
。如果要按原样保留原始文件,则应以二进制模式打开文件:
file.open(path, std::ios_base::in | std::ios_base::binary);
关于c++ - 为什么我的程序在Windows和Linux上产生关于使用ifstream读取文件的不同结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9817806/