Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open returns (-1) with O_CREAT when file already exists

Tags:

c

system-calls

That function saves an unsigned int array in a file. I want it to overwrite an existing file or to create it. If the file doesn't exist, it is filled correctly. If it already exists, it remains as it was : but I want it to be overwritten. That is why I use 'O_CREAT'.

int save_pic(t_bunny_pixelarray *pix, const char *filename, t_tekpaint *tekpaint) {
    unsigned int *pixels;
    int FD;
    int i = 0;
    if (!filename)
        return 1;
    if ((FD = open(filename, O_WRONLY | O_CREAT, S_IRUSR)) == -1)
        return 1;
    return 0;
}

(I write between the last return 1 and return 0).

If I do the following :

if ((FD = open(filename, O_WRONLY | O_CREAT, S_IRUSR)) == -1) {
    printf("error\n");                                                            
    return 1;
}

It prints error if files exists, and doesn't print error if file doesn't exist. I tried to change S_IRUSR to other possible values for I thought maybe the process had no right on the file or something but it doesn't change anything.

It acts like if I was using O_EXCL, which I obviously don't. MUST be a stupid thing. Thank you.

like image 993
NanoPish Avatar asked Oct 27 '25 05:10

NanoPish


1 Answers

S_IRUSR means read for user (so without write permission).

The first run the program create the file with permission -r--------
The second run fails with EPERM (Permission denied).

You should specify write access :

open(filename, O_WRONLY | O_CREAT, S_IWUSR)

or use the default umask using :

open(filename, O_WRONLY | O_CREAT)
like image 56
mpromonet Avatar answered Oct 29 '25 20:10

mpromonet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!