为什么 ifstream 的读数超出了 EOF?(即使没有打开文件)如何在EOF停止阅读

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

本文关键字:EOF 文件 ifstream 为什么      更新时间:2023-10-16

我只是用 fstream 测试了一些 IO 安全检查,并注意到我在外部寻找时没有得到任何标志(我期望 EOF,但我意识到标志仅在 IO 操作后设置?(当尝试读取超出文件大小时,我希望它会在 EOF 停止,但它继续从一些未知来源读取。 最后,我注意到您甚至不需要打开文件。 我必须这样做吗自己手动应用数学,这样它就不会读取过去的 EOF?以及它如何/为什么/在哪里读取文件?

#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 FilesWindowsPowerShellModules;C:Windows...
}

为什么 ifstream 的读数超出了 EOF?

我相信不会。
你是问为什么在你超越终点后bad()不是真的吗?

(即使没有打开文件(如何在EOF停止阅读?

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

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

file.read(data,size); // can read outside file
for(int i=0; i<size; i++)std::cout<<data[i]; // PSModulePath=C:Program FilesWindowsPowerShellModules;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];
    }
}