5

I am trying to do a simple comparison to be able to do something if the file type read is a directory.

Sample code :

int main()
{
  DIR *dir = opendir(".");
  struct dirent *dirent = readdir(dir);
  if (dirent->d_type == DT_DIR)
    //do something
  return 0;
}

Here is says:

DT_DIR not initialised

When I try to use brackets around as such: "DT_DIR" I get the following errors:

  • comparing pointer and integer

  • comparison with string literal results in undefined behavior

If I understand correctly I need to put DT_DIR in a char array? This is the first time I'm using these structs and functions.

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
raiskader
  • 89
  • 4
  • 16

1 Answers1

9

The macro DT_DIR is not part of the POSIX but a glibc extension. Define #define _GNU_SOURCE at the top before including headers to get it (or define _DEFAULT_SOURCE if your glibc version is >= 2.19). In fact d_type isn't even mentioned in POSIX's definition of struct dirent.

P.P
  • 117,907
  • 20
  • 175
  • 238