Reading directory contents on Linux

How can we read the contents (subdirectories and file names) of a directory using the C language on Linux.

+4
source share
3 answers

Here is a recursive program for recursively outputting the name of all subdirectories and files.
Usage: ./ a.out path name
Error conditions are not checked for the source path name specified as a command line argument.
The main stream of code:
All entries in the current directory are read.
if it is a directory name, its name is added to the path name, and the function is called recursively.
otherwise, the file names are printed.

Details of specific functions can be referenced on the corresponding manual pages, as indicated by dmuir:

#include<sys/stat.h> #include<unistd.h> #include<dirent.h> #include<error.h> int read(char *pth) { char path[1000]; strcpy(path,pth); DIR *dp; struct dirent *files; /*structure for storing inode numbers and files in dir struct dirent { ino_t d_ino; char d_name[NAME_MAX+1] } */ if((dp=opendir(path))==NULL) perror("dir\n"); char newp[1000]; struct stat buf; while((files=readdir(dp))!=NULL) { if(!strcmp(files->d_name,".") || !strcmp(files->d_name,"..")) continue; strcpy(newp,path); strcat(newp,"/"); strcat(newp,files->d_name); printf("%s\n",newp); //stat function return a structure of information about the file if(stat(newp,&buf)==-1) perror("stat"); if(S_ISDIR(buf.st_mode))// if directory, then add a "/" to current path { strcat(path,"/"); strcat(path,files->d_name); read(path); strcpy(path,pth); } } } int main(int argc,char *argv[]) { read(argv[1]); } 
+6
source

Relevant functions are opendir, readdir and closedir. I recommend "man opendir" etc.

+4
source

Here is the code that will do this (taken from the link ), I hope it helps you get started with what you are looking for.

 #include <ftw.h> #include <stdio.h> #include <sys/stat.h> int list(const char *name, const struct stat *status, int type); int main(int argc, char *argv[]) { if(argc == 1) ftw(".", list, 1); else ftw(argv[1], list, 1); return 0; } // FTW_F The object is a file // FTW_D ,, ,, ,, ,, directory // FTW_DNR ,, ,, ,, ,, directory that could not be read // FTW_SL ,, ,, ,, ,, symbolic link // FTW_NS The object is NOT a symbolic link and is one for // which stat() could not be executed int list(const char *name, const struct stat *status, int type) { if(type == FTW_NS) return 0; if(type == FTW_F) printf("0%3o\t%s\n", status->st_mode&0777, name); if(type == FTW_D && strcmp(".", name) != 0) printf("0%3o\t%s/\n", status->st_mode&0777, name); return 0; } 

Edit: ftw is what is used to work with the file system, for more information about this, see the ftw man page

+2
source

All Articles