Search code examples
cmkdir

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");

Solution

  • 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");
    }