扫描目录

对于目录的操作也类似于文件操作,通过一些库函数即可对目录进行扫描

1、opendir函数

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

函数原型如下:

# include <sys/types.h>
# include <dirent.h>

DIR *openrir(const char *name);

opendir在失败时返回一个空指针。注意,目录流使用一个底层文件描述符来访问目录本身,所以如果打开的文件过多,opendir可能会失败

2、readdir函数

readdir函数返回一个指针,该指针指向的结构里保存着目录流dirp中下一个目录项的有关资料。后续的readdir调用将返回后续的目录项。如果发生错误或者到达文件尾,readdir将返回NULL。

函数原型如下:

# include <sys/types.h>
# include <dirent.h>

struct dirent *readdir(DIR *dirp);

注意:如果在readdir函数扫描目录的同时还有其他进程在该目录里创建或删除文件,readdir将不保证能够列出该目录里的所有文件。

dirent结构中包含文件的一下部分:

  • ino_t   d_ino:文件的inode节点
  • char    d_name:文件的名字

3、teildir函数

teildir函数的返回值记录着一个目录流里的当前位置。可以在随后的seekdir调用中利用这个值来重置目录扫描到当前位置。

函数原型如下:

# include <sys/types.h>
# include <dirent.h>

long int teildir(DIR *dirp);

4、seekdir函数

seekdir函数的作用是设置目录流dirp的目录项指针。loc的值是用来设置指针位置,它应该通过前一个teildir调用获得。

函数原型如下:

# include <sys/types.h>
# include <dirent.h>

int closedir(DIR *dirp, long int loc);

5、closedir函数

closedir函数关闭一个目录流并释放与之相关的资源。它在执行成功时返回0,执行失败返回-1.

函数原型如下:

# include <sys/types.h>
# include <dirent.h>

int closedir(DIR *dirp);

示例:

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

void printdir(char *dir, int depth)
{
    DIR * dp;
    struct dirent *entry;//目录文件信息的存储格式 
    struct stat statbuf;

    if((dp = opendir(dir)) == NULL)//打开目录流 
    {
        printf("opendir error");
        return ;
    }
    //进入到目录dir中 
    chdir(dir);
     //entry保存目录中某一项文件的信息 
     //遍历该目录流,entry(即readdir返回值为NULL)为空时到达目录流结尾 
    while((entry = readdir(dp)) != NULL)
    {
		//lstat函数功能是获取文件信息,将当前文件的信息存储到statbuf中 
        lstat(entry->d_name,&statbuf);
        //S_ISDIR函数功能是判断一个文件是否为目录 
        if(S_ISDIR(statbuf.st_mode))
        {
            if(strcmp(".",entry->d_name) == 0 ||
                strcmp("..",entry->d_name) == 0)
            {
                continue;
            }
            //该文件是一个目录,继续调用printdir函数查看该目录下的文件 
            //depth用来控制空格数,例如最高层目录前空格数为0,目录级别每第一层输出前空格数加4 
                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()
    {
        printdir("/home",0);
        exit(0);
    }

猜你喜欢

转载自blog.csdn.net/qq_41727218/article/details/81295679
今日推荐