#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
const int INDENT = 4;
void printDir(const char* name , const int depth){
DIR* dir;
struct dirent* dt;
struct stat state;
int result , error;
extern int errno;
char* filename;
result = stat(name , &state);
if(0 != result){
error = errno;
perror(name);
}
if(!S_ISDIR(state.st_mode))
return;
printf("%*s%s/\n",depth,"",name);
dir = opendir(name);
if(NULL == dir )
return;
chdir(name);
while( NULL != (dt = readdir(dir))){
filename = dt->d_name;
if(strcmp("." , filename) && strcmp(".." ,filename )) {
stat(filename , &state);
if(S_ISDIR(state.st_mode)){
printDir(filename , depth+INDENT);
}else{
printf("%*s%s\n",depth+INDENT,"",filename);
}
}
}
chdir("..");
closedir(dir);
}
int main(int argc , char** argv){
char* rootdir;
if(2 == argc){
rootdir = *(argv + 1);
}else{
rootdir = ".";
}
printDir(rootdir , 0);
return 0;
}
c 遍历目录文件
最新推荐文章于 2024-05-23 13:47:29 发布