ifstream:如何判断指定的文件是否不存在 [英] ifstream: how to tell if specified file doesn't exist

查看:1283
本文介绍了ifstream:如何判断指定的文件是否不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个文件进行阅读。但是,在这个程序的上下文中,如果文件不存在就没关系,我只是继续。我想要能够识别错误是文件未找到,当错误是否则。

I want to open a file for reading. However, in the context of this program, it's OK if the file doesn't exist, I just move on. I want to be able to identify when the error is "file not found" and when the error is otherwise. Otherwise means I need to quit and error.

我没有看到用 fstream 这样做的明显方法。 。

I don't see an obvious way to do this with fstream.

我可以使用C的 open() perror()。我假设有一个 fstream 的方式来做到这一点。

I can do this with C's open() and perror(). I presumed that there was a fstream way to do this as well.

推荐答案

p>因为打开文件的结果是特定于操作系统的,我不认为标准C ++有任何方法来区分各种类型的错误。该文件打开或不打开。

Since the result of opening a file is OS-specific, I don't think standard C++ has any way to differentiate the various types of errors. The file either opens or it doesn't.

您可以尝试打开该文件进行阅读,如果它不打开,您知道它不存在或发生其他错误。然后再次,如果您尝试打开它以后写作,它失败,那可能属于其他类别。

You can try opening the file for reading, and if it doesn't open, you know it either doesn't exist or some other error happened. Then again, if you try to open it for writing afterwards and it fails, that might fall under the "something else" category.

这篇关于ifstream:如何判断指定的文件是否不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆