d_name, "..") to check...">

How can I check if a file name is a directory or not in C?

I use if(strstr(dir->d_name, ".") == NULL && strstr(dir->d_name, "..")

to check if its a directory / subdirectory, but this still prints some files that are not directories ... I am using direct structure and DIR.

+3


source to share


3 answers


strstr

searches for a substring within another string, so it returns a match for every name that contains one (zero or double) period.

You probably used strcmp

:

if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, ".."))
   .. not one of the default root folders ..

      



Before or after that, you can check if it's not a folder:

if (dir->d_type == DT_DIR)
  ..

      

or use stat

. (Note that d_type

may not be supported by some file system types.)

+3


source


I personally like stat () and fstat (). Then you look at the st_mode field of the output using macros like S_ISDIR (m).



+1


source


If you are working on Linux, you can use getdents

that include record type. Otherwise, you probably have to use stat

/lstat

to get the type information for each element.

0


source







All Articles