streamseekg()的实现在VS2012到2010之间有所不同

stream seekg() implementation varies from VS2012 to 2010

本文关键字:2010 之间 有所不同 VS2012 实现 streamseekg      更新时间:2023-10-16

我有一段旧代码,它在gcc VS2010上运行良好。我试图在VS2012中编译相同的代码。我知道我可以在任何地方设置为true,但这不是实际的代码。我缩短了代码以重现问题。

std::ifstream file_stream;
file_stream.open("C:\experiment\file.txt", std::ios_base::in);
std::istream& stream = file_stream;
bool done = false;
while(stream.good() || !done){
    int stream_position = stream.tellg();
    bool stream_failure = (stream_position == -1);
    bool stream_eof = stream.eof();
    std::string line;
    std::getline(stream, line);
    std::cout << stream_failure << stream_eof << std::endl;
    std::streampos pos = stream.tellg();
    if(pos == std::streampos(-1)){
        std::streampos copy = pos;
        stream.seekg(0, std::ios_base::end);
        pos = stream.tellg();
        stream.seekg(copy);
    }
}
std::getline(std::cin, std::string());
file_stream.close();

如果我将平台工具集更改为VS2010,它会工作并打印1而不是stream_eof
如果我将平台工具集更改为VS2012,则不会,并打印0而不是stream_eof在到达EOF 之后

如果我在cout后面放一个if(stream_eof)return 0;,它会在VS2010上返回,但不会在VS2012 中返回

这是C++03和C++11之间的区别之一。

在C++03中,当您在设置了任何错误位的流上调用seekg()时,它将失败,并且不执行任何其他操作。

在C++11中,seekg()首先无条件地清除eofbit,然后尝试按指示执行。在这种情况下,由于failbit也被设置,因此它失败,但eofbit被清除。

(顺便说一句,为什么你的循环首先被设置为读取文件末尾?使用通常的while(getline(stream, line))