Chinaunix首页 | 论坛 | 博客
  • 博客访问: 343122
  • 博文数量: 60
  • 博客积分: 1570
  • 博客等级: 上尉
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-02 23:37
文章分类

全部博文(60)

文章存档

2012年(2)

2010年(2)

2009年(56)

分类: LINUX

2009-11-17 22:42:11

判断一个文件是否存在,
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 函数。

 
阅读(1399) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~