如何检查文件是否存在于C + +与fstream :: open() [英] How to check if a file exists in C++ with fstream::open()

查看:801
本文介绍了如何检查文件是否存在于C + +与fstream :: open()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用fstream库来处理文件。基本上,我需要知道某个文件是否存在。在c ++文档在线,关于open(),它是:

I'm using fstream library to work with files. Basically, I need to know if a certain file exists or not. In c++ documentation online, about open(), it reads:


返回值

Return Value

none

如果函数未能打开一个文件,则将failbit状态标志设置为
(可能会抛出ios_base :: failure状态标志
是使用成员异常注册的)。

If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).

它说明未指定返回值。但是在失败的情况下,设置标志。我的问题是,我应该我然后访问该标志,或更好地问,我应该如何看到 open()是否成功。

It says not return value is specified. But in case of failure, a flag is set. My question is that, I should I then access that flag, or to better ask, how should I see if open() is successful or not.

我有这样的代码:

int Log::add()
{
    fstream fileStream;

    fileStream.open("logs.txt");
}


推荐答案

如果文件无法打开。所以你可以检查那个位:

It says it sets the failbit if the file couldn't be opened. So you can check for that bit:

fileStream.open("logs.txt");
if (fileStream.fail()) {
    // file could not be opened
}

其实,只要 if(fileStream)就可以在这里工作,因为 ios 基本类 ifstream ofstream fstream )有一个转换操作符 bool

Actually, just if (fileStream) would work here as well, since ios (a base class of ifstream, ofstream, and fstream) has a conversion operator to bool.

不要担心失败异常。您可以通过调用 ios :: exceptions 来请求异常抛出,但默认情况下不会抛出异常。

Don't worry about the failure exception. You can request exceptions to be thrown on failure by calling ios::exceptions but by default exceptions are not thrown on failure.

请注意,这并不会告诉您为什么无法打开该文件。可能是文件不存在,路径中的目录不存在,您没有权限打开文件,您的程序已达到其可以打开的文件数量的限制,因此上。没有可移植的方法来确定原因。

Note that this doesn't tell you why the file couldn't be opened. It could be that the file didn't exist, that a directory in the path didn't exist, you don't have permission to open the file, your program has reached the limit on the number of files it can open, and so on. There is no portable way to determine the reason.

这篇关于如何检查文件是否存在于C + +与fstream :: open()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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