gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:15:17 30 4
gpt4 key购买 nike

我只是用 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 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];
}
}

关于c++ - 为什么ifstream读取超出eof? (即使没有文件打开)如何在eof处停止阅读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57170270/

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