can't compare dirent->d_type to DT_DIR
Asked Answered
G

1

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.

Glarum answered 11/10, 2017 at 17:35 Comment(0)
M
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.

Matheson answered 11/10, 2017 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.