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

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

当前回答

对于那些喜欢刺激的人:

 boost::filesystem::exists(fileName)

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

 std::filesystem::exists(fileName)

其他回答

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
}

虽然有几种方法可以做到这一点,但对您的问题最有效的解决方案可能是使用fstream的预定义方法之一,例如good()。使用此方法可以检查指定的文件是否存在。

fstream file("file_name.txt");

if (file.good()) 
{
    std::cout << "file is good." << endl;
}
else 
{
    std::cout << "file isnt good" << endl;
}

我希望这对你有用。

windows下还有3个选项:

1

inline bool exist(const std::string& name)
{
    OFSTRUCT of_struct;
    return OpenFile(name.c_str(), &of_struct, OF_EXIST) != INVALID_HANDLE_VALUE && of_struct.nErrCode == 0;
}

2

inline bool exist(const std::string& name)
{
    HANDLE hFile = CreateFile(name.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile != NULL && hFile != INVALID_HANDLE)
    {
         CloseFile(hFile);
         return true;
    }
    return false;
}

3

inline bool exist(const std::string& name)
{
    return GetFileAttributes(name.c_str()) != INVALID_FILE_ATTRIBUTES;
}

你也可以使用bool b = std::ifstream('filename').good();。如果没有分支指令(比如if),它必须执行得更快,因为它需要被调用数千次。

备注:在c++ 14中,一旦文件系统TS完成并被采用,解决方案将使用:

std::experimental::filesystem::exists("helloworld.txt");

从c++ 17开始,只有:

std::filesystem::exists("helloworld.txt");