当seekg寻找文件末尾时,未设置failbit(C ++,Linux)

时间:2012-06-13 19:58:53

标签: c++

我看到我认为是istream :: seekg的奇怪行为。具体来说,它似乎 当我寻找一个明显偏离文件末尾的点时,不要设置failbit。

从文档中我可以看出,应该设置failbit,但事实并非如此。

任何人都可以解释这种行为吗?相关代码片段:

class Tester 
{

  ... 

  void testTriggered()
  {
    fs.open("/pathtofile/testFile.TEST", std::ios_base::in|std::ios_base::binary);
    prv_testbits("testTriggered(): OpeningFile");

    fs.seekg(2000,std::ios_base::beg);
    prv_testbits("testTriggered(): seekTwoThousand");
    int g = fs.tellg();
    std::cout << "get pointer is:" << g << std::endl; 
  }

  void prv_testbits(std::string msg){
    if (fs.fail()) {
      std::cout << msg << ": failbit set." << std::endl;
    } else {
      std::cout << msg << ": failbit NOT set." << std::endl;
    }
    if (fs.bad()) {
      std::cout << msg << ": badbit set." << std::endl;
    }else {
      std::cout << msg << ": badbit NOT set." << std::endl;
    }
    if (fs.eof()) {
      std::cout << msg << ": eofbit set." << std::endl;
    } else {
      std::cout << msg << ": eofbit NOT set." << std::endl;
    }
  }

   ....

 private:
  std::ifstream fs;
}; 

输入文件由20个字节组成:     0123456789abcdefghij

样本运行输出:

testTriggered(): OpeningFile: failbit NOT set.
testTriggered(): OpeningFile: badbit NOT set.
testTriggered(): OpeningFile: eofbit NOT set.
testTriggered(): seekTwoThousand: failbit NOT set.
testTriggered(): seekTwoThousand: badbit NOT set.
testTriggered(): seekTwoThousand: eofbit NOT set.
get pointer is:2000

g ++版本信息: $ g ++ -v 使用内置规格。 目标:x86_64-linux-gnu 配置为:../ src / configure -v --with-pkgversion ='Ubuntu 4.4.3-4ubuntu5'-with-gxx-include-dir = / usr / include / c ++ / 4.4 [snip] gcc版本4.4.3(Ubuntu 4.4.3-4ubuntu5)

$ uname -a Linux hostx 2.6.32-36-server#79-Ubuntu SMP Tue Nov 8月22日22:44:38 UTC 2011 x86_64 GNU / Linux

1 个答案:

答案 0 :(得分:4)

fseek()的开放组规范(可能用于实现fstream::seekg)是允许文件位置超出当前文件结尾所必需的:

  

fseek()函数应允许将文件位置指示符设置为超出文件中现有数据的末尾。如果此时稍后写入数据,则后续读取间隙中的数据应返回值为0的字节,直到数据实际写入间隙为止。

http://pubs.opengroup.org/onlinepubs/009696699/functions/fseek.html