C/C++判断文件是否存在

The following is the most common method for checking if file exist:

#include <sys/stat.h>

bool FileExist(const char* FileName)
{
    struct stat my_stat;
    return (stat(FileName, &my_stat) == 0);
}

//Example Usage
int main(int argc, char* argv[])
{
    bool v1 = FileExist("c:\\autoexec.bat");
    bool v2 = FileExist("c:\\nofile.bat");
    bool v3 = FileExist("c:\\config.sys");
    bool v4 = FileExist("c:\\nofile2.bat");
    return 0;
}

This method works on ALL platforms I have used (Windows, Unix, Linux).
And it does not require opening the file, which could cause problems on some platforms if the file has protected property settings.
This method works both in C and in C++.
Although stat is not part of the standard, it is supported by all major platforms and compilers.

原文地址:https://www.cnblogs.com/liuyunfeifei/p/2982937.html