为什么ifstream读取超出eof? (即使没有文件打开)如何在eof处停止阅读?

why does ifstream read beyond eof? (even if no file is open) how to stop reading at eof?

我只是用 fstream 测试了一些 io 安全检查,并注意到我在向外寻找时没有得到任何标志(我期待 eof,但我意识到标志只在 io 操作之后设置?)文件大小,我预计它会停在 eof,但它会继续从一些未知来​​源读取。最后我注意到你甚至不需要打开文件。我是否必须自己手动应用数学,这样它就不会读取过去的 eof?并且 how/why/where 是否正在读取文件?

#include <iostream>
#include <fstream>

void checkErrors(std::ifstream& f){
    std::cout<<"FLAGS: ";
    if(f.good()) std::cout<<"good";
    if(f.rdstate() & f.badbit) std::cout<<"badbit ";
    if(f.rdstate() & f.eofbit) std::cout<<"eofbit ";
    if(f.rdstate() & f.failbit) std::cout<<"failbit ";
    std::cout<<std::endl;
}

int main(){
    std::ifstream file;
//  file.open("abc.txt"); // don't even have to open any file

    file.seekg(100, file.beg); // can seek outside file
    std::cout<<file.tellg()<<std::endl; // 100 (if open else) -1
    checkErrors(file); // FLAGS: good (if open else) failbit

    int size = 200;
    char* data = new char[size];

    file.read(data,size); // can read outside file
    checkErrors(file); // FLAGS: eofbit failbit (if open else) failbit

    for(int i=0; i<size; i++)std::cout<<data[i]; // PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\...

}

why does ifstream read beyond eof?

我确定不会。
你是在问为什么你越过最后 bad() 就不是真的了吗?

(even if no file is open) how to stop reading at eof?

如果您尝试读取超出文件末尾的内容,则会出现错误。仅仅超越终点本身是不够的。但是在你超出末尾之后尝试访问数据应该会导致错误。

嗯,你看到这里有一个错误:

file.read(data,size); // can read outside file
for(int i=0; i<size; i++)std::cout<<data[i]; // PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\...

这应该写成:

if (file.read(data, size)) {
    // If you attempt to read and it works then you can print out
    // the data you read otherwise what is the point.

    // Also notice you can't gurantee that you got `size` bytes.
    // You should consult `gcount()` to get the number of characters read.

    for(int i = 0; i < file.gcount(); ++i) {
        std::cout << data[i];
    }
}