access函数在<unistd.h>头文件中,使用它可以非常方便的检查真实用户的权限。
有如下文件
1 2 3 4 5 |
yli@yli-desktop ~/test $ ll total 8 drwxrwxr-x 2 yli yli 4096 Sep 18 00:14 . drwxr-xr-x 70 yli yli 4096 Sep 18 00:13 .. -rw-rw-r-- 1 yli yli 0 Sep 18 00:14 a.txt |
用如下C++程序,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <cstdlib> #include <iostream> #include <unistd.h> #include <errno.h> using namespace std; /* * */ int main(int argc, char** argv) { // 检查文件是否存在 if (access("/home/yli/test/a.txt", F_OK) == 0) { cout << "the file exists" << endl; } if (access("/home/yli/test/a.txt", R_OK) == 0) { cout << "has read permission" << endl; } if (access("/home/yli/test/a.txt", W_OK) == 0) { cout << "has write permission" << endl; } if (access("/home/yli/test/a.txt", R_OK | W_OK) == 0) { cout << "has read and write permission" << endl; } if (access("/home/yli/test/a.txt", X_OK) == 0) { cout << "has exec permission" << endl; } else { cout << "no exec permission" << ((errno == EACCES) ? " EACCES" : "") << endl; } return 0; } |
得如下输出,
1 2 3 4 5 |
the file exists has read permission has write permission has read and write permission no exec permission EACCES |
清楚明了。