判断一个文件是否存在,
1. 可以使用access函数。
#include <unistd.h> int access(const char *pathname, int mode); |
RETURN VALUE
On success (all requested permissions granted), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or some other error occurred), -1 is returned, and errno is set appropriately.
mode参数说明:
F_OK tests for the existence of the file. R_OK, W_OK, and X_OK test
whether the file exists and grants read, write, and execute permissions, respec-tively.
示例代码:
#include <stdio.h> #include <stdlib.h> #include <unistd.h>
/* * return value: * 1: file exists * 0: file does not exist * */ int file_exist(const char *filename) { int ret;
ret = access(filename, F_OK); if (ret == 0) ret = 1; else ret = 0; return ret; }
int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s \n", argv[0]); exit(1); }
if (file_exist(argv[1])) printf("file exist: %s\n", argv[1]); else perror("file not exist:");
exit(0); }
|
不明白的地方:
Linux Programmer Manual 写到:
Warning: Using access() to check if a user is authorized to, for example, open a
file before actually doing so using open(2) creates a security hole, because the
user might exploit the short time interval between checking and opening the file
to manipulate it. For this reason, the use of this system call should be avoided.
google了好久,还是不明白这个安全漏洞是怎么回事。
现在就这样用这吧,以后搞明白了在另外考虑。
2. 另外可以使用 stat 函数。
阅读(1435) | 评论(0) | 转发(0) |