Let's create a mkdir utility

Let's create the mkdir utility in C. Create a file named mkdir.c and write the following code.

#include <stdio.h>

int main(int argc, char* argv[]) {
    printf("hello, world\n");

    return 0;
}

Run the program to confirm that the setup works.

$ gcc mkdir.c -o mkdir && ./mkdir
hello, world

Our mkdir utility requires one or more arguments representing the directories or folders that we want to create. If we don't pass any arguments, we need to guide the user with a help message. We can get the argument count from argc and the argument values from argv. The name of the executable is the first argument. So, argc needs to be greater than 1.

#include <stdio.h>

int main(int argc, char* argv[]) {
    if (argc == 1) {
        printf("Usage: mkdir [directory...]\n");
        return 1;
    }

    return 0;
}

Users can create one or more directories by passing the names or paths of the directories as arguments. So, we need to loop through the argv values and get the directory names.

#include <stdio.h>

int main(int argc, char* argv[]) {
    if (argc == 1) {
        printf("Usage: mkdir [directory...]\n");
        return 1;
    }

    for (int i = 1; i < argc; i++) {
        const char* path = argv[i];
    }

    return 0;
}

We can create a directory using the mkdir() function declared in the sys/stat.h header file. The function accepts a path or directory name and a permission mode. The function returns 0 on success and -1 on failure. So, we can write a condition to check the return value. If we get a return value of -1, it is a truthy value, and we can handle the error within the condition.

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

int main(int argc, char* argv[]) {
    if (argc == 1) {
        printf("Usage: mkdir [directory...]\n");
        return 1;
    }

    for (int i = 1; i < argc; i++) {
        const char* path = argv[i];

        if (mkdir(path, 0777) != -1) {
            perror(path);
            return 0;
        }
    }

    return 0;
}

Let's run the executable and confirm that it works.

$ gcc mkdir.c -o mkdir
./mkdir
Usage: mkdir [directory...]

$ ./mkdir abc
$ ./mkdir abc/xyz
$ ./mkdir def ghi

Comments