我有一个程序如下所示.为此,我有几个问题:
1).为什么它会在不同的平台上产生不同的结果? 我稍后会粘贴屏幕截图.
2).我正在使用fail()方法来检查"file.read()"是否失败.它是否正确? 我使用fail()方法,因为这个网页说:
如果设置了failbit或badbit,则该函数返回true.当在输入操作期间发生除了到达文件结尾之外的某些错误时,设置这些标志中的至少一个.
但后来我在这里阅读了关于istream :: read()的这个页面.它说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;
}
Run Code Online (Sandbox Code Playgroud)



这是否意味着正常的EOF情况也会导致fail()返回true?这似乎与"除了达到文件结束之外"相冲突.
我建议使用一个没有错误的引用.
http://en.cppreference.com/w/cpp/io/basic_ios/fail说:
true如果关联的流上发生错误,则返回.具体来说,返回trueifbadbit或failbitset inrdstate().
C++标准说:
返回:
true如果是failbit或badbit设置为rdstate().
没有"除文件结束之外"的东西.尝试读取文件末尾的操作也将导致failbit设置.将eofbit仅用于区分其他特定失败的原因(而不是像一些人认为,在第一有用).
我正在使用一种
fail()方法来检查"file.read()"是否失败.它是否正确?
你应该简单地测试转换为bool.
if(file) { // file is not in an error state
Run Code Online (Sandbox Code Playgroud)
它是同义词!fail(),但它更有用,因为你可以使用它来直接测试读操作的结果而不需要额外的括号(比如!(stream >> x).fail()变得笨拙):
if(file.read(fileBuf, fileLen)) { // read succeeded
Run Code Online (Sandbox Code Playgroud)
您会注意到,对流的所有读取操作都会返回流本身,这使您可以执行此操作.
为什么它会在不同的平台上产生不同的结果?
您在Windows和Linux之间看到的差异是因为文件在文本模式下打开:新行字符将由实现静默转换.这意味着组合"\r\n"(在Windows中用于换行)将在Windows中转换为单个'\n'字符,使文件只有8个字符.注意vim如何^M在第一行的末尾显示:这是'\r'部分.在Linux中,新行就是'\n'.
如果要保留原始文件,则应以二进制模式打开文件:
file.open(path, std::ios_base::in | std::ios_base::binary);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3114 次 |
| 最近记录: |