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

时间:2009-10-30 01:33:06

标签: c++ file

我想打开一个文件进行阅读。但是,在这个程序的上下文中,如果文件不存在就可以了,我继续。我希望能够识别错误何时“未找到文件”以及何时出现错误。否则意味着我需要退出并出错。

我没有看到使用fstream执行此操作的明显方法。


我可以使用C open()perror()执行此操作。我认为还有一种fstream方法可以做到这一点。

9 个答案:

答案 0 :(得分:55)

编辑:我已收到通知,这并不一定表明文件不存在,因为它可能会因访问权限或其他问题而被标记。

我知道我在回答这个问题的时候已经很晚了,但我认为无论如何我都会留下评论给任何人浏览。您可以使用ifstream的失败指示器来判断文件是否存在。

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

答案 1 :(得分:39)

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

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

如果您使用的是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 
    }
}

答案 2 :(得分:7)

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

您可以尝试打开文件进行读取,如果没有打开,您知道它不存在或发生其他错误。然后再次,如果你试图打开它后写,它失败了,那可能属于“别的”类别。

答案 3 :(得分:6)

http://www.cplusplus.com/forum/general/1796/

的简单方法
ifstream ifile(filename);
if (ifile) {
  // The file exists, and is open for input
}

答案 4 :(得分:5)

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

#include <sys/stat.h>

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

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

答案 5 :(得分:1)

更好的方法:

             Program:

             C:\Users\Matthew\Documents\project\homework\debug\

             File: minkernel \crts \ ucrt \ src \ appcrt \stdio\ fgets.cpp

             Line: 33

             Expression: stream.valid()

             Abort   Retry  Ignore

答案 6 :(得分:0)

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

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

答案 7 :(得分:0)

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

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

答案 8 :(得分:-1)

让我以实际运行为例:

  1. 文件不存在:

enter image description here

  1. 文件存在:

enter image description here

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