To create a directory on Linux using C, take a look at the following code.
#include <stdio.h> #include <sys/stat.h> int main(void) { char *foldername = "test_dir"; int status = mkdir(foldername, S_IRUSR | S_IWUSR | S_IXUSR); if(status == 0) { printf("Folder successfully created.\n"); } else { printf("Error: Folder creation failed.\n"); } return 0; }
How it works:
First I declared a variable foldername. This variable stores the name of the folder that I want to create.
Then I used the mkdir(foldername, permission) library functions from sys/stat.h. This function will return 0 if a folder is created or -1 on failure. I stored the return value on a variable status.
Then I checked the status variable to see if a folder is created(status == 0) or not(status == -1).
Here is used, S_IRUSR | S_IWUSR | S_IXUSR as permission. It means, the newly created directory will have read, write, and execute permission of the owner of the directory.
You can find a whole list of permission constants here. I am writing some common easy to remember ones here.
S_IRUSR - Read permission of the owner of the directory. S_IWUSR - Write permission of the owner of the directory. S_IXUSR - Execute permission of the owner of the directory. S_IRGRP - Read permission of the group. S_IWGRP - Write permission of the group. S_IXGRP - Execute permission of the group. S_IROTH - Read permission to others. S_IWOTH - Write permission to others. S_IXOTH - Execute permission to others.