gpt4 book ai didi

c++ - C++ 文件 IO 错误的 Try-Catch block 不起作用

转载 作者:可可西里 更新时间:2023-11-01 18:41:45 25 4
gpt4 key购买 nike

我是 C++ 错误处理领域的新手,但有人告诉我:
Checking for file existence in C++

...检查文件是否存在的最佳方法是使用 try-catch block 。从我对该主题的有限知识来看,这听起来是个不错的建议。我找到了这段代码:
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 的目录中运行程序,prog 不断向终端吐出空行。谁能知道为什么?

此外,也是一种检查文件是否存在的好方法,用于检查您真正想要打开和读取的文件(相对于您索引一堆文件并检查它们的方法)?

谢谢!

最佳答案

在 C++ 中,iostream 默认不抛出异常。你需要的是

ifstream myfile("test.txt");

if(myfile) {
// We have one
}
else {
// we dont
}

关于c++ - C++ 文件 IO 错误的 Try-Catch block 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3629321/

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