gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:04:57 25 4
gpt4 key购买 nike

我看到了 istream::seekg 的奇怪行为。具体来说,它似乎当我寻找明显远离文件末尾的点时,不要设置故障位。

根据我在文档中了解到的信息,应该设置故障位,但实际上并没有。

谁能解释这种行为?相关代码片段:

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;
};

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

sample 运行的输出:

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 -aLinux hostx 2.6.32-36-server #79-Ubuntu SMP 11 月 8 日星期二 22:44:38 UTC 2011 x86_64 GNU/Linux

最佳答案

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

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

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

关于c++ - 当 seekg 寻找超过文件末尾时未设置 failbit (C++,Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11022417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com