Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - fopen opening directories?

Tags:

c

linux

fopen

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.

like image 875
Daeto Avatar asked Mar 18 '17 15:03

Daeto


People also ask

Can fopen open a directory?

The fopen can't be used to create directories. This is because fopen function doesn't create or open folders, it only works with files. The above code creates a path to the file named 'filename'. The directory of the 'filename' is obtained using the 'dirname' function.

What is the return type of open () and fopen ()?

The key difference between the fopen() and the open() function in the Linux operating system is that the open() function is a low-level call, where the fopen() when called simply calls the open() function in the background and it returns a Filepointer directly.


1 Answers

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;
}
like image 79
emlai Avatar answered Sep 25 '22 13:09

emlai