Linux下判断文件或文件夹是否存在的方法


可以用access函数来判断。

 

int access(const char *pathname, int mode);

下面是对参数mode的说明。一般来说,判断文件或文件夹是否存在,取 mode=F_OK 就可以了。

mode说明
0 F_OK 只判断是否存在
2 R_OK 判断读取权限
4 W_OK 判断写入权限
6 X_OK 判断执行权限
(或者说是读写权限)

access函数返回0表示成功,否则失败。

示例:

test.cpp

  1. #include <unistd.h>  
  2. #include <iostream>  
  3. using namespace std; 
  4.  
  5. int main(int argc, char* argv[]) 
  6.         if(access(argv[1], F_OK) != 0) 
  7.         { 
  8.                 cout << argv[1] << " does not exist!" << endl; 
  9.         } 
  10.  
  11.         return 0; 
  12. }

编译:

g++ test.cpp -o test

运行:

./test /some/folder

结果:

/some/folder does not exist!

相关内容

    暂无相关文章