我想找到最快的方法来检查一个文件是否存在于标准c++ 11, 14, 17,或C。我有成千上万的文件,在对它们做一些事情之前,我需要检查它们是否都存在。在下面的函数中,我可以写什么来代替/* SOMETHING */ ?

inline bool exist(const std::string& name)
{
    /* SOMETHING */
}

当前回答

你可以使用std::ifstream,函数如is_open, fail,例如下面的代码(cout“open”表示文件是否存在):

引自以下答案

其他回答

inline bool exist(const std::string& name)
{
    ifstream file(name);
    if(!file)            // If the file was not found, then file is 0, i.e. !file=1 or true.
        return false;    // The file was not found.
    else                 // If the file was found, then file is non-0.
        return true;     // The file was found.
}

使用MFC可以实现以下功能

CFileStatus FileStatus;
BOOL bFileExists = CFile::GetStatus(FileName,FileStatus);

哪里的文件名是一个字符串表示文件,您正在检查的存在

对于那些喜欢刺激的人:

 boost::filesystem::exists(fileName)

或者,自ISO c++ 17开始:

 std::filesystem::exists(fileName)

我使用这段代码,到目前为止,它工作得很好。它没有使用c++的许多奇特的特性:

bool is_file_exist(const char *fileName)
{
    std::ifstream infile(fileName);
    return infile.good();
}
all_of (begin(R), end(R), [](auto&p){ exists(p); })

其中R是你的路径序列,exists()来自未来std或当前boost。如果你自己卷,简单点,

bool exists (string const& p) { return ifstream{p}; }

分支解决方案并不是绝对可怕的,它不会吞噬文件描述符,

bool exists (const char* p) {
    #if defined(_WIN32) || defined(_WIN64)
    return p && 0 != PathFileExists (p);
    #else
    struct stat sb;
    return p && 0 == stat (p, &sb);
    #endif
}