Reputation: 13
I have this assignment, part of it needs to create some files that have the name xNNNNNN, where NNNNNN is replaced by a random six-digit number and the files should be created in the random order in which their names are generated, I've already do that but the problem is that the files I get is a write protected but I want them to be write only, what I'm doing wrong ?? is it related to the flags or something else ?
here is what I write :
int file;
int fileName;
int counter;
char str1[5];
char str2[5];
int fileNum = atoi(argv[2]);
for (counter = 0; counter < fileNum ; counter++)
{
fileName = rand() % 900000 + 100000;
sprintf (str1, "%d", fileName); //write the value of r as a string in str
sprintf (str2, "%s%s", "x", str1);
printf ("%s\n" ,str2);
file = open (str2, O_WRONLY|O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);
if (file != -1)
{
//do something
}
}
Upvotes: 1
Views: 1980
Reputation: 213538
You want them to be write-only, but you pass read-only permissions to open()
:
file = open (str2, O_WRONLY|O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);
The permissions here are S_IRUSR | S_IRGRP | S_IROTH
. The O_WRONLY
flag is for permissions on the file descriptor itself, not permissions on the created file.
This does what you want:
file = open(str2, O_WRONLY|O_CREAT, 0222);
Note that 0222 = S_IWUSR | S_IWGRP | S_IWOTH
. I personally find octal much easier to read, but you may prefer the other notation.
Permissions on created files will be modified by removing bits set in the umask. If you really need the permissions to be 0222, and not, say, 0200, there are two ways:
#include <sys/stat.h>
int fdes;
fdes = open(str2, O_WRONLY|O_CREAT, 0222);
if (fdes < 0) abort();
fchmod(fdes, 0222);
#include <sys/stat.h>
mode_t saved_umask;
int fdes;
saved_umask = umask(0);
fdes = open(str2, O_WRONLY|O_CREAT, 0222);
umask(saved_umask);
Upvotes: 4