I am creating a file using open function and using O_CREAT | O_EXCEL . I have passed the mode as "0666" . But by masking finally the permission allotted to it is -rw-r--r-- and not the -rw-rw-rw- . Someone told me i can use umask (011) and then reset the original mask again . But i dont know how to pass this in c++ program. This is the small snippet of What i am doing .
# include <iostream>
# include <stdio.h>
# include <conio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main()
{
int fd = open("C:\\Users\\Ritesh\\Music\\music.txt", O_CREAT | O_EXCL, 0666);
getch();
return 0;
}
creates file C:\Users\Ritesh\Music\music.txt
with permission -rw-r--r-- .
I want it to be -rw-rw-rw-
mode_t old_mask;
old_mask = umask(011);
open( ... );
umask(old_mask);
The only thread-safe way to set file permissions to be what you want is to set them explicitly with chmod()
or fchmod()
after creating the file (example without error checking):
int fd = open("C:\\Users\\Ritesh\\Music\\music.txt", O_CREAT | O_EXCL, 0666);
fchmod(fd, 0666 );
If you use umask()
, you will change the umask
value for the entire process. If any other threads are running you risk files getting created with unexpected permissions, which could lead to a security issue or other problems. And any child process created while your changed umask
value is in effect will be created with an unexpected umask
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With