Linux C Traversal directory structure

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.