C语言读取文件夹内容
char dirPath[] ="/home/xxxx/TestFiles/chapeter4";
DIR* dir = opendir(dirPath);
struct dirent * dirent = readdir(dir);
while (dirent != NULL) {
printf("%s\n",dirent->d_name);
dirent = readdir(dir);
}
C语言遍历文件夹
void printNChar(int n){
int i;
for(i = 0 ; i < n ;i++){
printf("-");
}
}
/**
* @brief RecursiveReadfolder2
* @param n
* @param fd
* @param name
*/
void RecursiveReadfolder2(int n,int fd,const char* name){
struct stat buf;
if(fstatat(fd,name,&buf,AT_SYMLINK_NOFOLLOW)<0){
return;
}
if(S_ISDIR(buf.st_mode)){
int subfd = openat(fd,name,O_DIRECTORY|O_NOFOLLOW);
DIR* dir = fdopendir(subfd);
struct dirent * dirent = NULL;
while ((dirent = readdir(dir)) != NULL) {
printNChar(n);
printf("%s\n",dirent->d_name);
if(strcmp(dirent->d_name,".") != 0 && strcmp(dirent->d_name,"..") != 0)
RecursiveReadfolder2(n+2,subfd,dirent->d_name);
}
}/*else{
printNChar(n);
printf("%s\n",name);
}*/
}
void RecursiveReadfolder(const char* path){
struct stat buf;
int n=2;
if(lstat(path,&buf)<0){
return;
}
printf("%s\n",path);
if(S_ISDIR(buf.st_mode)){
int fd = open(path,O_DIRECTORY);
DIR* dir = fdopendir(fd);
struct dirent * dirent = NULL;
while ((dirent = readdir(dir)) != NULL) {
printNChar(n);
printf("%s\n",dirent->d_name);
if(strcmp(dirent->d_name,".") != 0 && strcmp(dirent->d_name,"..") != 0)
RecursiveReadfolder2(n+2,fd,dirent->d_name);
}
}/*else{
printNChar(n);
printf("%s\n",path);
}*/
}