#include <stdio.h>
#include <dirent.h>    		 	//头文件

int ReadDir(char *path) 		//读取文件
{
        DIR *dir;			
        char pathname[255];		//目录的全名,=当前目录名+子目录名
        if((dir = opendir(path))==0)	//无法打开则跳过
        {       
                printf("open %s failed!\n",path);       return -1;
        }       

        struct dirent *stdir; 

        while(1)
        {       
                if((stdir = readdir(dir))==0)           break;  //遍历完一整个文件夹就停止循环
                if(stdir->d_type == 8)							//文件则输出
                {       
                        printf("name: %25s/%s\n",path,stdir->d_name);
                }       
                else //if(stdir->d_type == 4)					//文件夹则递归进行下一轮,打开文件夹
                {       
                        sprintf(pathname,"%s%s",path,stdir->d_name);		//获得目录全名(当前目录名 + 子目录名)
                        ReadDir(pathname);
                }       
        }       
        closedir(dir);		//关闭目录
}

int main(int argc,char *argv[])
{       
        if(argc != 2)
        {       
                printf("本程序用于读取目录下所有文件,path为目录\n"); 
                printf("fg : ./aa path\n");             return -1;
        }       

        ReadDir(argv[1]);
}

实验结果

在这里插入图片描述

GitHub 加速计划 / li / linux-dash
6
1
下载
A beautiful web dashboard for Linux
最近提交(Master分支:3 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐