C++ ifstream:如何判断指定的文件是否不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1647557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:44:59  来源:igfitidea点击:

ifstream: how to tell if specified file doesn't exist

c++file

提问by Paul Nathan

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.

我想打开一个文件进行阅读。但是,在这个程序的上下文中,如果文件不存在也没关系,我只是继续。我希望能够确定错误何时是“找不到文件”,何时是其他错误。否则意味着我需要退出并出错。

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

我没有看到用fstream.



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

我可以用 Copen()perror(). 我认为也有一种fstream方法可以做到这一点。

采纳答案by Cogwheel

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.

由于打开文件的结果是特定于操作系统的,我认为标准 C++ 无法区分各种类型的错误。该文件要么打开,要么不打开。

You can try opening the file for reading, and if it doesn't open (ifstream::is_open()returns false), 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::is_open()返回false),您就知道它要么不存在,要么发生了其他一些错误。再说一次,如果您之后尝试打开它进行写作并且失败了,那可能属于“其他”类别。

回答by SwarthyMantooth

EDIT: I've been notified that this does not necessarily indicate a file does not exist, as it may be flagged due to access permissions or other issues as well.

编辑:我已被告知这不一定表示文件不存在,因为它也可能因访问权限或其他问题而被标记。

I know I'm extremely late in answering this, but I figured I'd leave a comment anyway for anyone browsing. You can use ifstream's fail indicator to tell if a file exists.

我知道我回答这个问题很晚,但我想无论如何我都会为任何浏览的人发表评论。您可以使用 ifstream 的失败指示器来判断文件是否存在。

ifstream myFile("filename.txt");
    if(myFile.fail()){
        //File does not exist code here
    }
//otherwise, file exists

回答by AraK

I don't think you can know if "the file doesn't exist". You could use is_open() for generic checking:

我认为您无法知道“文件不存在”。您可以使用 is_open() 进行通用检查:

ofstream file(....);
if(!file.is_open())
{
  // error! maybe the file doesn't exist.
}

If you are using boostyou could use boost::filesystem:

如果您正在使用,boost您可以使用boost::filesystem

#include <boost/filesystem.hpp>
int main()
{
    boost::filesystem::path myfile("test.dat");

    if( !boost::filesystem::exists(myfile) )
    {
        // what do you want to do if the file doesn't exist 
    }
}

回答by LI Xuhong

A simple way from http://www.cplusplus.com/forum/general/1796/

来自http://www.cplusplus.com/forum/general/1796/的简单方法

ifstream ifile(filename);
if (ifile) {
  // The file exists, and is open for input
}

回答by Erik Garrison

You can use stat, which should be portable across platforms and is in the standard C library:

您可以使用 stat,它应该可以跨平台移植并且在标准 C 库中:

#include <sys/stat.h>

bool FileExists(string filename) {
    struct stat fileInfo;
    return stat(filename.c_str(), &fileInfo) == 0;
}

If stat returns 0, the file (or directory) exists, otherwise it doesn't. I assume that you'll have to have access permissions on all directories in the file's path. I haven't tested portability, but this pagesuggests it shouldn't be an issue.

如果 stat 返回 0,则文件(或目录)存在,否则不存在。我假设您必须对文件路径中的所有目录具有访问权限。我还没有测试可移植性,但这个页面表明它不应该是一个问题。

回答by user1633272

A better way:

更好的方法:

std::ifstream stream;
stream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
stream.open(fileName, std::ios::binary);

回答by Jayhello

Let's me give example with real running:

让我举个实际运行的例子:

  1. file does't exist:
  1. 文件不存在:

enter image description here

在此处输入图片说明

  1. file exist:
  1. 文件存在:

enter image description here

在此处输入图片说明

see http://www.cplusplus.com/reference/fstream/ifstream/for more information about its public function.

有关其公共功能的更多信息,请参见http://www.cplusplus.com/reference/fstream/ifstream/

回答by Curious

The function std::fstream::good()returns falsefor multiple reasons, including when the file does not exist. Is not that enough?

该函数因多种原因std::fstream::good()返回false,包括文件不存在时。这还不够吗?

std::fstreaminheritsthis function from std::ios.

std::fstream继承此功能std::ios

回答by Arun

Straight way without creating ifstream object.

无需创建 ifstream 对象的直接方式。

if (!std::ifstream(filename))
{
     // error! file doesn't exist.
}