linux access()函数和readdir()函数



linux access()函数和readdir()函数
 
1  linux access()函数和readdir()函数
1.1  access()
access函数的原型如下:
int access(const char *pathname, int mode);
 
此函数是用来获得调用进程对pathname所指向的文件(regular)或者是目录(directory)的访问权限。
pathname: 文件或者是目录路径
 
mode:访问模式。可以F_OK,或者是F_OK和R_OK, W_OK,and X_OK的或(|)。F_OK,表示pathname所指向文件是否存在。
 
写一段程序,判断目录是否存在,如下:
  www.2cto.com  
#include <errno.h>
 
#include <unistd.h>
 
#include <stdio.h>
 
int main()
{
   int err = 0;
 
   err = access("/home/test" , F_OK);
 
   if ( err !=0 ){
 
         printf("erro!%d:%s\n", errno , strerror(errno ));
  www.2cto.com  
         mkdir("/home/test", 0777);
 
         printf("erro!%d : %s\n" , errno, strerror(errno));
 
    }else
 
         printf("direxit!\n");
 
   return 0;
}
 
我们在/home目录下面创建一个test文件,然后测试上面的程序。
 
1、  如果传入的pathname是”/home/test",路径最后一个字符串不是斜杠’/’,结果如下:
 
root@VM-Ubuntu203001:~/test#./a.out
 
dir exit!  www.2cto.com  
 
因为 test在/home下面是个文件,access判断这个文件已经存在,是正确的。
 
2、  如果传入的pathname是”/home/test/",路径最后一个字符串是斜杠’/’,结果如下:
 
root@VM-Ubuntu203001:~/test#./a.out
 
erro!20:Nota directory
 
erro! 17 : File exists
 
    测试结果是,access 把/home目录下面的test文件当做目录了,最后发现test不是目录,所以报错了。
 
经过查找文档,得知:如果linux文件路径的最后一个字符是斜杠’/’,那么linux会把这个路径当做目录路径来处理,而不管路径中的目录名实际上是个已经存在的文件名。
 
1.2        readdir()
函数原型:
  www.2cto.com  
DIR *opendir(const char *dirpath);
 
struct dirent *readdir(DIR *dirp);
 
opendir()函数打开一个dirpath指向的目录,如果成功返回一个DIR类型的指针,DIR指针指向dirpath目录下的第一个条目。readdir() 会返回这个条目的信息,以struct dirent形式展现,然后DIR指针会指向下一个条目。
 
这里需要注意的是:DIR所遍历条目,是没有排序的,和ls –f 列出的顺序一致。
 

相关内容

    暂无相关文章