3

I'm using if(strstr(dir->d_name, ".") == NULL && strstr(dir->d_name, "..")to check if its a directory/subdirectory, but this is still printing out some files that are not directories...Im using the direct struct and DIR.

mr nooby noob
  • 1,860
  • 5
  • 33
  • 56
  • 1
    Can you show a bit more code? – Paul Rooney May 05 '15 at 23:07
  • 1
    Depending on operating system, if you read [the `readdir` manual page](http://man7.org/linux/man-pages/man3/readdir.3.html) you will see that it have a member called `d_type` which is the type of "file" the directory entry is. – Some programmer dude May 05 '15 at 23:10
  • See [Checking if a directory exists in Unix system call](http://stackoverflow.com/questions/3828192/checking-if-a-directory-exists-in-unix-system-call) for the answer when not working with `readdir()` et al, or when your system provides only the minimal information that the POSIX specification for `struct dirent` from [``](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/dirent.h.html) defines (which is `d_name` and `d_ino`). More accommodating systems may provide the file type in extended information that is stored directly in the `struct dirent` structure. – Jonathan Leffler May 06 '15 at 00:30

3 Answers3

4

strstr searches for a substring inside another string, so it will return a match for every name that contains a single (well, or a double) period.

You probably meant to use strcmp:

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

Before or after this, you can check if it is a folder or not:

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

or use stat. (Note that d_type may not be supported by certain file system types.)

Jongware
  • 22,200
  • 8
  • 54
  • 100
1

Personally, I like stat() and fstat(). You then look at the st_mode field of the output with macros like S_ISDIR(m).

Arlie Stephens
  • 1,146
  • 6
  • 20
0

If you're on Linux, you can use getdents which include entry type. Otherwise you'll probably have to use stat/lstat to get type info for every item.

che
  • 12,097
  • 7
  • 42
  • 71