user3368561
user3368561

Reputation: 819

Unintuitive behavior of open with flags DIRECTORY and O_CREAT

I'm running Ubuntu 16.04 with kernel version 4.8.0 and glibc version 2.23. When I execute open with flags O_DIRECTORY and O_CREAT and the directory does not exist, a regular file is created instead of a directory. What workarounds exist to fix that unintuitive behavior?

Upvotes: 1

Views: 75

Answers (1)

Martin Rosenau
Martin Rosenau

Reputation: 18523

When I understand the manpage of open correctly the combination of O_DIRECTORY and O_CREAT is not intended:

O_DIRECTORY should fail if the file name does not specify a directory. I interpret "a directory" as "an existing directory" here.

You might use mkdir first. mkdir will return an error code if the directory already exists. You simply ignore the value returned by mkdir. Then you open the file with O_DIRECTORY:

mkdir(the_file_name, your_desired_mode);
f = open(the_file_name, O_DIRECTORY);

Upvotes: 3

Related Questions