c linux 文件文件夹遍历

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

void listFiles(const char *path) {
    struct dirent *entry;
    DIR *dir = opendir(path);

    if (dir == NULL) {
        perror("Error opening directory");
        exit(EXIT_FAILURE);
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }
        // Check if the entry is a directory and recursively list its contents
        if (entry->d_type == DT_DIR) {
            char subpath[256];
            printf("dir %s\n", entry->d_name);
            snprintf(subpath, sizeof(subpath), "%s/%s", path, entry->d_name);
            listFiles(subpath);
        }
        else printf("file %s\n", entry->d_name);
    
    }

    closedir(dir);
}

int main() {
    const char *folderPath = "."; // Change this to the desired folder path
    listFiles(folderPath);

    return 0;
}
相关推荐
量子炒饭大师6 分钟前
Cyber骇客的逻辑节点美学 ——【初阶数据结构与算法】二叉树
c语言·数据结构·c++·链表·排序算法
課代表16 分钟前
从初等数学到高等数学
算法·微积分·函数·极限·导数·积分·方程
ullio19 分钟前
arc206d - LIS ∩ LDS
算法
oMcLin20 分钟前
CentOS 7 频繁出现 “Connection Refused” 错误的原因分析与解决
linux·运维·centos
等等小何44 分钟前
leetcode1593拆分字符串使唯一子字符串数目最大
算法
量子炒饭大师1 小时前
Cyber骇客神经塔尖协议 ——【初阶数据结构与算法】堆
c语言·数据结构·c++·二叉树·github·
饭九钦vlog1 小时前
银河麒麟修复openssh升级脚本
linux·运维
航Hang*1 小时前
第1章:初识Linux系统——第13节:总复习②
linux·笔记·学习·centos
Amy_au1 小时前
Linux week 01
linux·运维·服务器
王老师青少年编程2 小时前
2025年12月GESP(C++二级): 环保能量球
c++·算法·gesp·csp·信奥赛·二级·环保能量球