[代码实例][Linux系统编程]列出目录下的文件和子目录

本文介绍如何使用C语言中的opendir与readdir函数来遍历指定目录下的所有文件及子目录,通过示例代码展示了从打开目录到读取每个条目的完整过程。

系统调用


#include <dirent.h>

DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);

代码实例


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

#include <dirent.h>

void list_files(const char * dir_path);

int main(int argc, char * argv[])
{
    if(argc > 1 && strcmp(argv[1], "--help") == 0)
    {
        printf("Usage: %s [dir...]\n", argv[0]);
        return EXIT_SUCCESS;
    }

    if(argc == 1)
        list_files(".");
    else
        for(int i = 1; i < argc; i++)
            list_files(argv[i]);

    return EXIT_SUCCESS;
}

void list_files(const char * dir_path)
{
    DIR * dirp;
    struct dirent * dp;
    bool is_current;

    is_current = 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;

        if(!is_current)
        {
            printf("%s/", dir_path);
        }

        printf("%s\n", dp->d_name);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值