文件存在吗?

进行文件读取的时候,经常要判断文件是否存在。
以下代码实现了 Visual C++,GCC 不同编译器的处理。 
当然,如果有更多不同平台的代码,为了能更好的维护,将程序放到不同的文件里,然后预编译(precompile)。 
除了打开、关闭、读写文件,关于文件的其他操作(新建文件夹、移动、创建软链接等),C++ 还没有纳入标准,不知道C++17 会不会加入。想要跨平台的话,可以使用 boost::filesystem。这里是 std::experimental::filesystem,很多东西是从 boost 借鉴学来的。这里 http://en.cppreference.com/w/cpp/experimental/fs/exists 是判断文件是否存在的函数。

Windows 上判断一个文件是否存在,只要看 FILE 是否能以 read 方式打开。打开再关闭,效率低下。
Linux 上有所不同,因为存在 Readable | Writable | eXcutable 权限的问题。如果 FILE 存在但没有可读权限,以上面方式判断是错误的。Windows 上的文件在 Linux 里全是可读可写可执行的,这时,需要使用 access 函数了,该函数需要 #include <unistd.h>,access 函数的介绍在这里

C code snippet 如下:

#include <stdio.h>

#ifdef __GNUC__
#include <unistd.h>

bool exist(char* filename)
{
if(access(filename,F_OK)==0)
return true; // file exists!
return false;
}

#elif defined _WIN32

bool exist(char* filename)
{
FILE* pf=fopen(filename,"r");
if(!pf)
{
fclose(pf);
return true;
}
else
return false;
}

#else
#error Unknown compiler!

#endif


int main(int argc,char* argv[])
{
if(argc!=2)
  {
    printf("Implimentation: To judge whether the list file exists.\n")
    return 0;
  } 
    if(exist(argv[1]))
printf("File <%s> exists!\n",argv[1]);
else
printf("File <%s> doesn't exist!\n",argv[1]);

return 0;
}



原文地址:https://www.cnblogs.com/Martinium/p/does_file_exist.html