Operating System - Linux
1827331 Members
6286 Online
109963 Solutions
New Discussion

printig files in a directory

 
SOLVED
Go to solution
Henry Chua
Super Advisor

printig files in a directory

Hi all,

I am using C to read and print files in a directory but i do not want to print the directories within it. I am using readdir(), is there anyway to do this?

Thanks
Henry
3 REPLIES 3
Hemmetter
Esteemed Contributor

Re: printig files in a directory

Hi Henry,

You have to check every "dirent entry" with
stat(2) / fstat(2) against its st_mode .

rgds
HGH
H.Merijn Brand (procura
Honored Contributor

Re: printig files in a directory

is C a prerequisite? Why not the easy way: perl or sh

# perl -MFile::Find -le'find(sub{-d and return;print$File::Find::name},@ARGV)' $HOME, /tmp

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Peter Godron
Honored Contributor
Solution

Re: printig files in a directory

Henry,
after some modifcations:
#include
#include
#include
#include

main()
{
DIR *dirp;
struct dirent *dp;
struct stat buf;

printf("\tFiles:\n");
dirp = opendir(".");
while (dp = readdir(dirp)) {
if (stat(dp->d_name,&buf) == 0)
if(buf.st_mode & S_IFREG) printf("%s\n", dp->d_name);
}
return closedir(dirp);
}