How can we read the contents (subdirectories and filenames) of a directory using C language in Linux.
Cat. The simplest way to view text files in Linux is the cat command. It displays the complete contents in the command line without using inputs to scroll through it. Here is an example of using the cat command to view the Linux version by displaying the contents of the /proc/version file.
Listing a Directory's Contents To see a list of the contents of a directory, type the ls command (short for list) at the % prompt.
To see them in the terminal, you use the "ls" command, which is used to list files and directories. So, when I type "ls" and press "Enter" we see the same folders that we do in the Finder window.
How can I list directories only in Linux? Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only.
Here is a recursive program to print the name of all subdirectories and files recursively.
Usage: ./a.out path name
Error conditions are not checked for initial path name supplied as command line argument.
Basic flow of code:
All the entries in current directory are read.
if it is directory name, its name is added to path name and and function is called recursively.
else name of the files are printed.
Details about the particular functions can be referenced in respective man pages as pointed 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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With