Skip to content
Advertisement

how to determine directory or file in linux in c

I want to print only file names without printing Directory Names. So, I implement this function

JavaScript

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?

Advertisement

Answer

What you are looking for is stat or one of its variants. Specifically look at the st_mode field of struct stat. The macro you are interested in is S_ISDIR(x).

Find below your modified code that demonstrates what you want:

JavaScript

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 in struct dirent (which is not part of POSIX but is part of Linux).

With that said the code would be the following.

JavaScript

It is a lot cleaner, no need for malloc.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement