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>   #include <iostream>  
  2. using namespace std;   
  3. int main(int argc, char* argv[])  { 
  4.         if(access(argv[1], F_OK) != 0)          { 
  5.                 cout << argv[1] << " does not exist!" << endl;          } 
  6.           return 0; 
  7. }

编译:

g++ test.cpp -o test

运行:

./test /some/folder

结果:

/some/folder does not exist!

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/65323.html