Traversing the directory structure to find files is a very common feature, and today describes the way to traverse the Linux directory structure using Linux C:
Linux provides several system calls for direct directory reads and operations:
DIR * OPENDIR (const char * pathname);
struct dirent * READDIR (DIR * dir_handle);
int Closedir (dir * dir);
int stat (const char *file_name, struct stat *buf);
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <dirent.h>//related functions that include directory operations
/**
* @Param Pathname The directory full path name to traverse
* @Param Depth Current traversal level, initially 0
*/
void Printdir (const char * pathname, const int depth) {dir * dir;struct dirent * de;struct stat Fs;int i = 0;if (dir = Open Dir (pathname)) = = NULL) {printf ("open dir%s error \ r \ n", pathname); return;} ChDir (pathname); while ((De = Readdir (dir)) = NULL) {if (strcmp (De->d_name, ".") = = 0 | | strcmp (De->d_name, "..") = = 0) {continue;} if (stat (de->d_name, &fs) = =-1) {perror ("Fstat error"); continue;} if (S_isdir (Fs.st_mode)) {
/**
* If the current path is a directory, call the Printdir function recursively
*/for (i=0;i<depth;++i) {printf ("");} printf ("%s\r\n", De->d_name);p Rintdir (de->d_name, depth + 4);} Else{for (i=0;i<depth;++i) {printf ("");} printf ("%s\r\n", De->d_name);}}
ChDir (".."); Closedir (dir); return;} int main (int argc, char * * argv) {printdir ("/root/projects", 0); return 0;}
Linux comes with directory traversal functions
int Scandir (const char *dir,struct dirent **namelist,int (*filter) (const void *b),
Int (* Compare) (const struct Dirent * *, const struct dirent * *));
int Alphasort (const void *a, const void *b);
int Versionsort (const void *a, const void *b);
See man for how to use a specific function
Linux C Traversal directory structure