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

发布于 2024-09-17 11:05:01 字数 1214 浏览 9 评论 0 原文

我对 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 不存在的目录中运行程序,程序不断向终端吐出空行。谁能弄清楚为什么吗?

这也是检查您实际想要打开和读取的文件是否存在的好方法(而不是索引一堆文件并检查它们的方法)?

谢谢!

I'm very new to the world of C++ error handling, but I was told here:
Checking for file existence in C++

...that the best way to checks for file existence was with a try-catch block. From my limited knowledge on the topic, this sounds like sound advice. I located this snippet of code:
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;
}

...but when I compile it using

g++ -Wall -pedantic -o test_prog main.cc

And run the program in a directory where test.txt does not exist, the prog keeps spitting out empty lines to the terminal. Can anyone figure out why?

Also is this a good way to check for file existence for a file you actually want to open and read from (versus just something where your indexing a bunch of files and checking them over)?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月竹挽风 2024-09-24 11:05:01

在 C++ 中,iostream 默认情况下不会引发异常。你需要的是

ifstream myfile("test.txt");

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

In C++ iostreams do not throw exeptions by default. What you need is

ifstream myfile("test.txt");

if(myfile) {
   // We have one
}
else {
   // we dont
}
爱已欠费 2024-09-24 11:05:01

默认情况下,fstream 对象不会抛出异常。您需要使用void异常(iostate except);来设置异常行为。您可以使用 iostate exceptions ( ) const; 获取当前设置。稍微改变一下你的代码:

#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace std;

int main () 
{
  try{
      char buffer[256];
      ifstream myfile ("test.txt");
      myfile.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
      while (myfile)
      {
        myfile.getline (buffer,100);
        cout << buffer << endl;
      }
      myfile.close();

  }catch(std::exception const& e){
     cout << "There was an error: " << e.what() << endl;
  }
  return 0;
}

By default the fstream objects do not throw. You need to use void exceptions ( iostate except ); to set the exception behavior. You can fetch the current settings using iostate exceptions ( ) const;. Change your code just a bit:

#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace std;

int main () 
{
  try{
      char buffer[256];
      ifstream myfile ("test.txt");
      myfile.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
      while (myfile)
      {
        myfile.getline (buffer,100);
        cout << buffer << endl;
      }
      myfile.close();

  }catch(std::exception const& e){
     cout << "There was an error: " << e.what() << endl;
  }
  return 0;
}
維他命╮ 2024-09-24 11:05:01

首先,为了让 try 块发挥作用,您需要为流启用异常。

其次,像这样的循环:

  while (! myfile.eof() )

只会带来麻烦,你在这里看到了这一点。问题(在本例中)是,当文件无法打开时,eof 将永远不会收到信号——您无法/不会到达文件末尾,因为 没有文件。因此,您的循环将永远运行,对不存在的文件的末尾进行存在主义搜索。修复循环,事情很快就会变得更好:

 char buffer[256];
 ifstream myfile ("test.txt");

 while (myfile.getline(buffer,100))
 {
   cout << buffer << endl;
 }

当你在做的时候,多做一点修复不会有什么坏处(除非你真的打算使用分配给的空间的一半以下你的缓冲区):

 char buffer[256];
 ifstream myfile ("test.txt");

 while (myfile.getline(buffer,sizeof(buffer)))
 {
   cout << buffer << endl;
 }

或者,当然,完全消除问题:

std::string buffer;
ifstream myfile("test.txt");
while (getline(myfile, buffer))
    cout << buffer << "\n";

编辑:请注意,这些(至少目前)都不依赖于异常。如果我们成功地从输入读取一行,它们都会被设置为将一行写入输出。如果文件没有打开,循环体就不会执行,因为我们将无法从没有打开的文件中读取数据。如果我们想打印一条错误消息,告诉用户文件未打开,我们必须与上面的内容分开处理。例如:

ifstream myfile("test.txt");

if (!myfile) {
    std::cerr << "File failed to open";
    return FAIL;
}

while (std::getline(myfile // ...

First of all, for the try block to do any good, you need to enable exceptions for the stream.

Second, a loop like:

  while (! myfile.eof() )

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:

 char buffer[256];
 ifstream myfile ("test.txt");

 while (myfile.getline(buffer,100))
 {
   cout << buffer << endl;
 }

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):

 char buffer[256];
 ifstream myfile ("test.txt");

 while (myfile.getline(buffer,sizeof(buffer)))
 {
   cout << buffer << endl;
 }

Or, of course, eliminate the problem entirely:

std::string buffer;
ifstream myfile("test.txt");
while (getline(myfile, buffer))
    cout << buffer << "\n";

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:

ifstream myfile("test.txt");

if (!myfile) {
    std::cerr << "File failed to open";
    return FAIL;
}

while (std::getline(myfile // ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文