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.
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.
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.
The C standard doesn't mention anything about fopen
ing 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With