[代码实例][Linux系统编程]遍历目录

本文介绍了一个使用C语言编写的程序,该程序能够遍历指定路径下的所有文件,并打印出每个文件的完整路径。程序支持相对路径和绝对路径输入,并通过递归方式处理子目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>

#include <limits.h>
#include <dirent.h>


#define MIN(x,y)    (((x) < (y)) ? (x) : (y))

#define IS_APATH(p)  (*(p) == '/')
#define IS_RPATH(p)  (!(IS_APATH(p)))

void list_files(const char * dir_path);

int main(int argc, char * argv[])
{
    char path[PATH_MAX] = {0};

    if((argc == 2 && strcmp(argv[1], "--help") == 0)
        || argc != 2)
    {
        printf("Usage: %s <path>\n", argv[0]);
        return EXIT_SUCCESS;
    }

    if(strlen(argv[1]) >= PATH_MAX)
    {
        fprintf(stderr, "Path length is too long!\n");
        return EXIT_FAILURE;
    }

    if(IS_RPATH(argv[1]))
        realpath(argv[1], path);
    else
        strncpy(path, argv[1], PATH_MAX);

    list_files(path);

    return EXIT_SUCCESS;
}

void list_files(const char * dir_path)
{
    DIR * dirp;
    struct dirent * dp;
    bool is_root;
    char path[PATH_MAX] = {0};

    is_root = strcmp(dir_path, "/") == 0;

    if((dirp = opendir(dir_path)) == NULL)
    {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    while(true)
    {
        errno = 0;
        if((dp = readdir(dirp)) == NULL)
            break;

        if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
            continue;


        snprintf(path, PATH_MAX, "%s/%s", (is_root ? "" : dir_path), dp->d_name);
        if(dp->d_type == DT_DIR)
            list_files(path);
        else
            printf("%s\n", path);          
    }

    if(closedir(dirp) != 0)
    {
        perror("closedir");
        exit(EXIT_FAILURE);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值