为什么 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?以及它如何/为什么/在哪里读取文件?
#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];
}
}
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 如何在 EOF 之前从文件中读取并将其放入字符串中?
- 如何在从文件中读取整数时使用 file.eof()?
- 文件处理,eof() 定义
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- 为什么 ifstream 的读数超出了 EOF?(即使没有打开文件)如何在EOF停止阅读
- 如何将EOF(文件结尾)放入代码::块中?
- .EOF 在读取文件时导致 Seg 错误:FIXXED
- 输入文件读取错误的值,eof 控制循环不会结束
- C OOP,读取文件的问题,EOF使用了两次,排行榜
- 文件设置正确,但eof()和peek()意外地从新流返回了错误的值
- C++和 eof 中的文件读取
- 文件I/O Infinite循环C EOF
- 在读取C 文件时跳过EOF
- 在C++中的文件中使用eof()
- 如何在 EOF (C++) 之前读取多个块中的文件
- 如何在使用ifstream读取txt文件时检查EOF
- 逐行计算文件:EOF 重复最后一个数字(不能使用中断)
- C++:FStream认为它已经达到了二进制文件的EOF
- C ++ .eof.未读取文件的最后一个值