作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我只是用 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/
我是一名优秀的程序员,十分优秀!