Linux C reads the folder below to use the struct struct dirent, in header # include <dirent.h>, as follows:
1#include <dirent.h>2 structdirent3 {4 LongD_ino;/*inode Number Index node*/5off_t D_off;/*offset to this dirent in the directory file*/6Unsigned ShortD_reclen;/*length of this d_name filename long*/7UnsignedCharD_type;/*The type of d_name file type*/8 CharD_name [name_max+1];/*File name (null-terminated) file name, maximum 255 characters*/9}
Where D_type indicates the type of file: File (8), directory (4), linked file (10), and so on.
The following program recursively reads all filenames under a folder and its subfolders:
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<dirent.h>#include<unistd.h>intReadFileList (Char*basepath) {DIR*dir; structDirent *ptr; Char Base[ +]; if((Dir=opendir (basepath)) = =NULL) {Perror ("Open dir error ..."); Exit (1); } while((Ptr=readdir (dir))! =NULL) { if(strcmp (Ptr->d_name,".")==0|| strcmp (Ptr->d_name,"..")==0)///Current dir OR parrent dir Continue; Else if(Ptr->d_type = =8)///fileprintf"d_name:%s/%s\n",basepath,ptr->d_name); Else if(Ptr->d_type = =Ten)///Link Fileprintf"d_name:%s/%s\n",basepath,ptr->d_name); Else if(Ptr->d_type = =4)///dir{memset (Base,' /',sizeof(Base)); strcpy (Base, BasePath); strcat (Base,"/"); strcat (Base,ptr->d_name); ReadFileList (Base); }} closedir (dir); return 1;}intMainvoid) {DIR*dir; Charbasepath[ +]; //get the current absoulte pathmemset (BasePath,' /',sizeof(BasePath)); GETCWD (BasePath,999); printf ("The current dir is:%s\n", BasePath); //get the file list//memset (BasePath, ' n ', sizeof (BasePath)); //strcpy (BasePath, "./xl");readfilelist (BasePath); return 0;}
Execution output:
Linux C Read the file name of all files (including subfolders) under the folder (GO)