fstream EOF意外引发异常

编程入门 行业动态 更新时间:2024-10-09 03:28:28
本文介绍了fstream EOF意外引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题与上一个。我想打开并读取文件。我希望在无法打开文件时引发异常,但我不希望EOF引发异常。 fstream似乎可以让您独立控制是否在EOF,失败和其他不良事件上引发了异常,但是EOF似乎也倾向于映射到不良和/或失败异常。

My question is very similar to a previous one. I want to open and read a file. I want exceptions thrown if the file can't be opened, but I don't want exceptions thrown on EOF. fstreams seem to give you independent control over whether exceptions are thrown on EOF, on failures, and on other bad things, but it appears that EOF tends to also get mapped to the bad and/or fail exceptions.

这是我尝试做的一个精简示例。如果文件包含某个单词,函数f()应该返回true;如果文件中不包含某个单词,则该函数返回false;如果(例如)该文件不存在,则抛出异常。

Here's a stripped-down example of what I was trying to do. The function f() is supposed to return true if a file contains a certain word, false if it doesn't, and throw an exception if (say) the file doesn't exist.

#include <iostream> #include <fstream> #include <string> using namespace std; bool f(const char *file) { ifstream ifs; string word; ifs.exceptions(ifstream::failbit | ifstream::badbit); ifs.open(file); while(ifs >> word) { if(word == "foo") return true; } return false; } int main(int argc, char **argv) { try { bool r = f(argv[1]); cout << "f returned " << r << endl; } catch(...) { cerr << "exception" << endl; } }

但这不起作用,因为基本的fstream读取使用操作符>>显然是EOF设置错误或失败位的操作之一。如果文件存在并且不包含 foo,则该函数不会根据需要返回false,而是引发异常。

But it doesn't work, because basic fstream reading using operator>> is evidently one of the operations for which EOF sets the bad or the fail bit. If the file exists and does not contain "foo" the function does not return false as desired, but rather throws an exception.

推荐答案

如果目标是仅在打开文件时出现问题时才引发异常,为什么不写:

If the goal is to throw an exception only in case of a problem when opening the file, why not write:

bool f(const char *file) { ifstream ifs; string word; ifs.open(file); if (ifs.fail()) // throw only when needed throw std::exception("Cannot open file !"); // more accurate exception while (ifs >> word) { if (word == "foo") return true; } return false; }

您当然可以设置:

ifs.exceptions(ifstream::badbit);

在开放前或开放后,抛出异常,以防万一在阅读过程中发生了某些非常糟糕的事情。

before or after the the open, to throw an exception in case something really bad would happen during the reading.

更多推荐

fstream EOF意外引发异常

本文发布于:2023-11-25 06:28:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   意外   fstream   EOF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!