Search code examples
clinuxfopen

c - fopen opening directories?


I am using fopen() to determine whether I'm opening a file or a directory like this:

FILE *f;

f = fopen(path, "r");

if (f != NULL){

// found file

}

else {

// found a directory

}

And path is currently a path pointing to a directory, not a file and it looks something like this:

/home/me/Desktop/newfolder

However, when I run the code, it says that it found a file even though it's pointing to a folder and thus it should return NULL pointer, or not?

I'm working on Ubuntu.


Solution

  • The C standard doesn't mention anything about fopening directories.

    But http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html says the following (emphasis mine):

    The fopen() function will fail if:
    […]
    [EISDIR] The named file is a directory and mode requires write access.

    So if you change fopen(path, "r") to e.g. fopen(path, "r+") then it should fail if path refers to a directory:

    bool isDirectory(const char* path) {
        FILE *f = fopen(path, "r+");
        if (f) {
            fclose(f);
            return false;
        }
        return errno == EISDIR;
    }