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;
}
相关推荐
列逍19 小时前
Linux进程(三)
linux·运维·服务器·环境变量·命令行参数
Savior`L20 小时前
二分算法及常见用法
数据结构·c++·算法
水天需01020 小时前
VS Code Ctrl+Shift+V 预览 Markdown 无效的解决方案
linux
吃西瓜的年年20 小时前
1. 初识C语言
c语言·开发语言
mmz120720 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻21 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
永远都不秃头的程序员(互关)21 小时前
C语言 基本语法
c语言·开发语言
甄心爱学习1 天前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~1 天前
排序---常用排序算法汇总
数据结构·算法·排序算法