I want to print only file names without printing Directory Names. So, I implement this function
void list_file(char* directory){
DIR *d;
struct dirent *dir;
d = opendir(directory);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%c", dir->d_name[(int)strlen(dir->d_name)]);
if(dir->d_name[(int)strlen(dir->d_name)-2] != '/')
printf("%s\n", dir->d_name);
}
closedir(d);
}
}
I checked that Directory names ends with '/' character. So, I checked that if there are '/' character at the end of name, don't print that name but when I run the function, all of them is printed in selected directory?
Can you lead me that how can I check the end of Directory name?
What you are looking for is
stat
or one of its variants. Specifically look at thest_mode
field ofstruct stat
. The macro you are interested in isS_ISDIR(x)
.Find below your modified code that demonstrates what you want:
I have removed your first print as it was printing the null terminating character of the string.
Update:
As pointed out in the comments since we are dealing with Linux you can use the
d_type
field instruct dirent
(which is not part of POSIX but is part of Linux).With that said the code would be the following.
It is a lot cleaner, no need for
malloc
.Try using either of
stat, fstat, lstat
as required. This is used to get the file status.Usage:
stat() stats the file pointed to by path and fills in buf.
lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
All of them return a
stat
structure, which contains the following fields:From this try doing:
Compare the value with
S_IFDIR
to check if it is a directory.For more refer to :
man 2 stat
Using the
struct stat
can also help you because it contains many different information of a file.man readdir
on Linux: