Zhe Sheng Lim
Zhe Sheng Lim

Reputation: 314

Does open(filepath, O_WRONLY|O_EXCL) return a value if filepath exists?

I know that open(filepath, O_WRONLY|O_EXCL) will fail if filepath exists, but does it return anything?

Now say if I want to know if a file exists, and would like to print a message if it does, should I include the O_EXCL flag in the open() command above?

Edit: I guess I made a mistake, and I was supposed to use open(filepath, O_CREAT|O_EXCL)

Upvotes: 1

Views: 922

Answers (4)

chqrlie
chqrlie

Reputation: 145287

open(filepath, O_WRONLY|O_EXCL) will not fail if filepath exists, it will fail if it does not exist or if you do not have write access.

O_EXCL should only be used with O_CREAT and an extra argument must then be passed to specify the mode bits for the file to create:

int hd = open(filepath, O_WRONLY | O_CREAT | O_EXCL, 0644);

hd will have a negative value in case of failure and errno will be set to indicate the error cause. Use perror() to report the failure with an explicit error message.

You can also test file existence and write access with access(), but it is not appropriate for your use case as the file could be created by a concurrent process between the test with access and the call to open (among other reasons).

Upvotes: 3

user3629249
user3629249

Reputation: 16540

from the MAN page for open():

O_EXCL Ensure that this call creates the file: if this flag is speci‐ fied in conjunction with O_CREAT, and pathname already exists, then open() fails with the error EEXIST.

          When these two flags are specified, symbolic links are not  fol‐
          lowed: if pathname is a symbolic link, then open() fails regard‐
          less of where the symbolic link points.

          In general, the behavior of O_EXCL is undefined if  it  is  used
          without  O_CREAT.   There  is  one  exception:  on Linux 2.6 and
          later, O_EXCL can be used without O_CREAT if pathname refers  to
          a  block  device.   If  the block device is in use by the system
          (e.g., mounted), open() fails with the error EBUSY.

Therefore, your premise that it fails if the file already exist is not quite correct.

However, when it fails: (per the MAN page)

open(), openat(), and creat() return the new file descriptor, or -1  if
   an error occurred (in which case, errno is set appropriately).

Upvotes: 0

kabanus
kabanus

Reputation: 25980

An important note from the manual:

In general, the behavior of O_EXCL is undefined if it is used without O_CREAT. There is one exception: on Linux 2.6 and later, O_EXCL can be used without O_CREAT if pathname refers to a block device.

So barring one use case, your command invokes undefined behavior.

Upvotes: 1

Jens
Jens

Reputation: 72746

If open fails for any reason, it will return -1 and set errno to indicate the cause. The details are in your open(2) manual page. Type man 2 open in any Unixy system.

Upvotes: 0

Related Questions