显然,在 Linux (Centos 7, g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)) 上,您可以在打开以供阅读的文件中寻找荒谬的偏移量。我可以自己获取文件长度并检查偏移量,但是 seekg 不应该失败吗?
这个程序说明了。未检测到错误条件,但文件的长度远小于 999999 字节。
#include <iostream>
#include <fstream>
int main(int argc, char **argv) {
std::ifstream f("./tstseek.cpp",std::ios::in);
if(!f.seekg(9999999)) {
std::cerr << "SEEK FAILED" << std::endl;
}
long int pos = f.tellg();
if(f.bad() || f.fail()) {
std::cerr << "SEEK FAILED" << std::endl;
}
if(f.eof()) {
std::cerr << "EOF AFTER SEEK" << std::endl;
}
std::string s;
std::getline(f,s);
if(f.bad() || f.fail()) {
std::cerr << "getline failed" << std::endl;
}
if(f.eof()) {
std::cerr << "EOF after getline" << std::endl;
}
std::streamsize bytesread = f.gcount();
std::cerr << "Position after seekg(9999999) = " << pos << std::endl
<< "bytes read = " << bytesread << std::endl
<< "string=[" << s << "]" << std::endl;
}