GGWP
GGWP

Reputation: 13

error handling mkdir and chdir in C?

I do not understand why after creating directory mkdir return different values. In this example i'm trying to make a directory if not so error handle otherwise go to this directory if not so error handle.

But it's not working as I want! It shows me 'failed to create' but actually creates the directory. If I read reference right it returns 0 when successes.

Code:

    char* dirName = "Output";
    FILE *output;

    if(!mkdir(dirName))
        if(chdir(dirName))
            printf("Permission to open a new directory is denied");
    else
        printf("Permission to create a new directory is denied");

Upvotes: 1

Views: 3569

Answers (3)

chqrlie
chqrlie

Reputation: 144923

As correctly diagnosed by John Carpenter, the else relates to the second if. Use braces to avoid this bug known as the dangling else issue.

There is another issue in your code: under Linux or BSD, the prototype for mkdir is:

#include <sys/stat.h>
#include <sys/types.h>

int mkdir(const char *path, mode_t mode);

Do you include the system header files?

Not passing proper permissions, such as 0777 invokes undefined behavior, the syscall wrapper will pass indeterminate permissions, creating the directory with inconsistent permissions.

Here is a corrected version:

const char *dirName = "Output";

if (!mkdir(dirName, 0777)) {
    if (chdir(dirName)) {
        printf("Permission to open a new directory is denied");
    }
} else {
    printf("Permission to create a new directory is denied");
}

Upvotes: 1

Frank Bryce
Frank Bryce

Reputation: 8446

It looks like you need curly braces around the if statement bodies so that the else is bound to the correct if statement.

Upvotes: 3

Mike Nakis
Mike Nakis

Reputation: 62045

According to the documentation of mkdir:

Upon successful completion, mkdir() shall return 0. Otherwise, -1 shall be returned, no directory shall be created, and errno shall be set to indicate the error.

Now, remember, in C 0 evaluates to false, non-zero evaluates to true. So, when you check if( mkdir( ... ) ) you are essentially asking if mkdir returned non-zero. And -1 is non-zero, so you are asking whether mkdir() failed, not whether mkdir() succeeded.

What you want to do instead is if( mkdir ( ... ) == 0 ).

Also, in the event of failure, you have no reason to suppose that the reason of the failure was an "access denied" error. Check errno and report the correct error accordingly.

Upvotes: 2

Related Questions