设为首页 加入收藏

TOP

文件和目录(二)
2019-09-19 11:10:32 】 浏览:76
Tags:文件 目录
e); //成功返回指针,失败返回NULL struct dirent *readdir(DIR *dirp); //成功返回指针,失败返回NULL int closedir(DIR *dirp); //成功返回0,失败返回-1 /* On Linux, the dirent structure is defined as follows: */ struct dirent { ino_t d_ino; /* inode number */ off_t d_off; /* offset to the next dirent */ unsigned short d_reclen; /* length of this record */ unsigned char d_type; /* type of file; not supported by all file system types */ char d_name[256]; /* filename */ }; /* d_type value is defined as follows */ DT_BLK This is a block device. DT_CHR This is a character device. DT_DIR This is a directory. DT_FIFO This is a named pipe (FIFO). DT_LNK This is a symbolic link. DT_REG This is a regular file. DT_SOCK This is a Unix domain socket. DT_UNKNOWN The file type is unknown.

目录操作示例代码:递归遍历目录,打印所有文件路径

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

void display_dir(char *dir_path)
{
    DIR *dir_ptr;
    int dir_len;
    struct dirent *file_info;
    char sub_dir[256];

    if (dir_path == NULL)
    {
        return;
    }

    dir_ptr = opendir(dir_path);
    dir_len = strlen(dir_path);

    if (dir_path[dir_len - 1] == '/')
    {
        dir_path[dir_len - 1] = '\0'; //统一输出方式,避免出现dir//file.txt的现象
    }

    while (file_info = readdir(dir_ptr))
    {
        if (strcmp(file_info->d_name, ".") == 0 || strcmp(file_info->d_name, "..") == 0)
            continue;

        switch (file_info->d_type)
        {
        case DT_DIR:
            sprintf(sub_dir, "%s/%s", dir_path, file_info->d_name);
            display_dir(sub_dir);
            break;
        case DT_REG:
        case DT_BLK:
        case DT_CHR:
        case DT_FIFO:
        case DT_LNK:
            printf("%s/%s\n", dir_path, file_info->d_name);
            break;
        default:
            break;
        }
    }

    closedir(dir_ptr);
}

int main(int argc, char *argv[])
{
    display_dir(argv[1]);

    return 0;
}

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Linux五种IO模型 下一篇时间获取函数

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目