How to create a copyright directory using C on Posix

I am trying to write a simple C program that creates directories (clone mkdir.). This is what I have so far:

#include <stdlib.h> #include <sys/stat.h> // mkdir #include <stdio.h> // perror mode_t getumask() { mode_t mask = umask(0); umask (mask); return mask; } int main(int argc, const char *argv[]) { mode_t mask = getumask(); printf("%i",mask); if (mkdir("trial",mask) == -1) { perror(argv[0]); exit(EXIT_FAILURE); } return 0; } 

This code creates a directory with d--------- , but I want it to create it using drwxr-xr-x , like mkdir do? What am I doing wrong here?

Edit: This is a working solution for me:

 int main(int argc, const char *argv[]) { if (mkdir("trial",0777) == -1) { perror(argv[0]); exit(EXIT_FAILURE); } return 0; } 

Setting permissions according to umask is automatically processed. Therefore, I only needed to call mkdir with full permissions, and it would be shredded according to the current umask.

+6
source share
2 answers

As Eric says, umask is an addition to the real permission mode that you get. Therefore, instead of passing the mask directly to mkdir() , you should go 0777-mask to mkdir() .

0
source

You seem to misunderstand what umask used for. It sets / retrieves the process file mode creation mask, which, in turn, is used to turn off bits in the file mode that you specify in calls like mkdir , for example this (pseduo-code):

 real_mode = requested_mode & ~umask 

So, in your code, since you pass the value of umask itself, you end up giving permissions as zero, which is exactly what you see.

Instead, you must specify the necessary permissions when calling mkdir , for example:

 mkdir("trial", 0755) 
+7
source

Source: https://habr.com/ru/post/913164/


All Articles