cocoz1
cocoz1

Reputation: 127

Listing a directory's content and checking if the element is a file or a directory (C)

I've been trying to find a way to map a directory's content plus a check whether the found "element" is either a file or a directory.

I've tried all the "solutions" found here: How can I check if a directory exists?, How do you check if a directory exists on Windows in C? and Checking if a file is a directory or just a file

(My post here is not a duplicate, therefore)

Nothing was working for me. I'm on Windows 10. I'm not a fan of these windows libraries, anyway. That's why I'm looking for a way that only standard C. Here's my code so far:

struct dirent *de;
DIR *dr = opendir(opts->dirname);

#define DF_ISDIR 0x100
#define DF_ISFILE 0x200
#define DF_NOEXIST 0x400


while ((de = readdir(dr)) != NULL) {
    int exists = df_isdirectory(de->d_name);
    printf("[%s]: '%s'\n", exists == DF_ISDIR ? "DIR" : exists == DF_ISFILE ? "FILE" : "WHATEVER", de->d_name);
}

and

int df_isdirectory(const char *name) {
assert(name != NULL);

DIR *dp = NULL;
if (_access(name, F_OK) == 0) {
    if ((dp = opendir(name)) != NULL) {
        closedir(dp);
        return DF_ISDIR; //  element is directory
    } else {
        return DF_ISFILE; // element is a file
    }
}

return DF_NOEXIST; // element is whatever

}

It gives me the folliwing output:

enter image description here

As we can see, the program detects that .. and . as dirs, but not a single element in my directory. Even though "another" and "dfgsdgf" ARE DIRECTORIES!

enter image description here

So, why doesn't it consider my actual directories a directory? Side note: One directory ("dfgsdgf") is empty, the other one ("another") is filled with 2 files.

After spending so much time, and trying a ton of "working" solutions, I am slowing getting tired of this. I want a detailed explanation WHY MY CODE DOESN'T WORK AS EXPECTED and a clear code snippet THAT WORKS 100%.

PS: My testing dir is C:\test
My exe file is not located in the same directory.

Thanks, and have a nice day! ~Sebastian

Upvotes: 1

Views: 455

Answers (1)

Ctx
Ctx

Reputation: 18410

Here, you open the directory given in your opts structure:

DIR *dr = opendir(opts->dirname);

the content of opts->dirname is C:\test. However, here:

if ((dp = opendir(name)) != NULL) {

you try to open a directory entry relative to your cwd (which is somewhere else). Indeed already your _access() check fails due to that.

Try calling

chdir(opts->dirname);

before your while() loop or build a full path in a string to pass it to _access() and opendir() in your df_isdirectory() function.

Upvotes: 1

Related Questions