C++ 的 Try-Catch 块文件 IO 错误不起作用
我对 C++ 错误处理领域非常陌生,但这里告诉我:
检查 C++ 中的文件是否存在
...这是检查文件是否存在的最佳方法文件的存在是通过 try-catch 块来实现的。从我对这个主题的有限了解来看,这听起来是合理的建议。我找到了这段代码:
http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Readafileintrycatchblock.htm
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
try{
char buffer[256];
ifstream myfile ("test.txt");
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
}catch(...){
cout << "There was an error !\n";
}
return 0;
}
...但是当我使用编译它
g++ -Wall -pedantic -o test_prog main.cc
并在 test.txt 不存在的目录中运行程序,程序不断向终端吐出空行。谁能弄清楚为什么吗?
这也是检查您实际想要打开和读取的文件是否存在的好方法(而不是索引一堆文件并检查它们的方法)?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,iostream 默认情况下不会引发异常。你需要的是
In C++ iostreams do not throw exeptions by default. What you need is
默认情况下,
fstream
对象不会抛出异常。您需要使用void异常(iostate except);
来设置异常行为。您可以使用 iostate exceptions ( ) const; 获取当前设置。稍微改变一下你的代码:By default the
fstream
objects do not throw. You need to usevoid exceptions ( iostate except );
to set the exception behavior. You can fetch the current settings usingiostate exceptions ( ) const;
. Change your code just a bit:首先,为了让
try
块发挥作用,您需要为流启用异常。其次,像这样的循环:
只会带来麻烦,你在这里看到了这一点。问题(在本例中)是,当文件无法打开时,
eof
将永远不会收到信号——您无法/不会到达文件末尾,因为 没有文件。因此,您的循环将永远运行,对不存在的文件的末尾进行存在主义搜索。修复循环,事情很快就会变得更好:当你在做的时候,多做一点修复不会有什么坏处(除非你真的打算使用分配给的空间的一半以下你的缓冲区):
或者,当然,完全消除问题:
编辑:请注意,这些(至少目前)都不依赖于异常。如果我们成功地从输入读取一行,它们都会被设置为将一行写入输出。如果文件没有打开,循环体就不会执行,因为我们将无法从没有打开的文件中读取数据。如果我们想打印一条错误消息,告诉用户文件未打开,我们必须与上面的内容分开处理。例如:
First of all, for the
try
block to do any good, you need to enable exceptions for the stream.Second, a loop like:
Will lead to nothing but trouble, and you're seeing that here. The problem (in this case) is that when the file failed to open,
eof
will never be signaled -- you can't/don't reach the end of the file because there is no file. Therefore, your loop runs forever, on an existentialist search for the end of a nonexistent file. Fix the loop, and things get better in a hurry:While you're at it, a bit more fixing wouldn't hurt (unless you really meant to use less than half of the space you allocated for your buffer):
Or, of course, eliminate the problem entirely:
Edit: note that none of these (at least currently) depends on exceptions at all. They're all set up to write a line to the output if we succeeded in our attempt at reading a line from the input. If the file didn't open, the body of the loop simply won't execute, because we won't be able to read from a file that didn't open. If we want to print an error message telling the user that the file didn't open, we'd have to handle that separately from what's above. For example: