文件操作之3_扫描目录

来源:互联网 发布:淘宝双11抢购技巧 编辑:程序博客网 时间:2024/05/20 22:27

用到的系统调用函数如下:

lstat,opendir、readdir、chdir函数

1. lstat函数

函数原型:

     #include<unistd.h>

     #include <sys/stat.h>

     #include<sys/types.h>

     int  lstat(const char *path,struct stat *buf);

          lstat返回的是该符号链接本身的信息,stat结构成员如下:

st_mode      文件权限和文件类型信息

st_ino           与该文件关联的inode

st_dev           保存文件的设备

st_uid            文件属主的UID号

st_gid            文件属主的GID号

......

stat结构中返回的st_mode 标志以及与之关联的宏,他们定义在sys/stat.h中。


2. opendir函数

函数原型:

      #include <sys/types.h>

      #include <dirent.h>

      DIR *opendir(const char *name);

            opendir函数的作用是打开一个目录并建立一个目录流。如果哟成功,它返回一个指向DIR结构的指针,该指针用于读取目录数据项。


3. readdir 函数

函数原型:

     #include<sys/types.h>

     #include <dirent.h>

    struct dirent *readdir(DIR *dirp);

dirent结构中包含的目录项内容以下部分:

ino_t d_ino: 文件的inode节点号。

char d_name[]:文件的名字。

测试函数:

#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

void printdir(char *dir,int depth)
{
   DIR *dp;
   struct dirent *entry;
   struct stat statbuf;
   if((dp = opendir(dir))== NULL)
   {
        //fprintf(stderr,"cannot open directory: %s\n",dir);
        return;
   }
   chdir(dir);
   while((entry = readdir(dp))!=NULL)
   {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode))
        {
            if(strcmp(".",entry->d_name)==0 || strcmp("..",entry->d_name)==0)
                continue;
            printf("%*s%s/\n",depth,"",entry->d_name);
            printdir(entry->d_name,depth+4);
        }
        else printf("%*s%s\n",depth,"",entry->d_name);
   }
   chdir("..");
   closedir(dp);
}
int main()
{
   printf("directory scan of /home:\n");
   printdir("/home/zhangxm/c_programmer",0);
   printf("done.\n");
   exit(0);
}

函数结果:

zhangxm@zhangxm:~/c_programmer/dir_printdir$ ./printdir
directory scan of /home:
dir_read/
    read.c
    read
    read.txt
dir_chown/
    unlink.c
    rmdir
.......

0 0