本文介绍了当seekg查找超过文件末尾时,未设置failbit(C ++,Linux)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm seeing what I think is odd behaviour of istream::seekg. Specifically, it appears toNOT set the failbit when I seek to a point that is clearly way off the end of the file.

在文档中,failbit应该设置,但它不是。

From what I can tell in the documentation, the failbit should be set, yet it is not.

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

Can anyone explain this behaviour? snippet of relevant code:

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

input file consists of twenty bytes: 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
使用内置specs。
目标: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)

g++ version info:$ g++ -vUsing built-in specs.Target: x86_64-linux-gnuConfigured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.3-4ubuntu5' -with-gxx-include-dir=/usr/include/c++/4.4 [snip]gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)

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

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

推荐答案

需要 fseek()(可能用于实现 fstream :: seekg )的Open Group规范允许超出当前文件结束位置的文件位置:

The Open Group specification for fseek() (likely used to implement fstream::seekg) is required to allow file positions beyond the current end-of-file:

这篇关于当seekg查找超过文件末尾时,未设置failbit(C ++,Linux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:07