mr nooby noob
mr nooby noob

Reputation: 2253

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

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.

Upvotes: 4

Views: 4333

Answers (3)

Arlie Stephens
Arlie Stephens

Reputation: 1176

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

Upvotes: 2

Jongware
Jongware

Reputation: 22447

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.)

Upvotes: 4

che
che

Reputation: 12263

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.

Upvotes: 1

Related Questions