File Already Exists
The target file or directory already exists and the operation requires that it not exist. This occurs with exclusive file creation (O_CREAT | O_EXCL), mkdir on an existing directory, and hard-linking to an existing path.
- 1Opening a file with O_CREAT | O_EXCL when the file already exists.
- 2Running mkdir for a directory that already exists.
- 3Creating a hard link to a path that already exists.
- 4A race condition where two processes try to create the same file simultaneously.
Creating a directory that already exists.
$ mkdir /tmp/existing-dir $ mkdir /tmp/existing-dir mkdir: cannot create directory '/tmp/existing-dir': File exists
expected output
mkdir: cannot create directory '/tmp/existing-dir': File exists
Fix 1
Use mkdir -p to create directories idempotently
WHEN When the directory may or may not already exist
$ mkdir -p /tmp/myapp/logs # Does not fail if already exists
Why this works
The -p flag makes mkdir succeed even if the directory already exists.
Fix 2
Use O_CREAT without O_EXCL to open-or-create a file
WHEN When you want to create a file if it does not exist, or open it if it does
int fd = open("/tmp/myfile", O_RDWR | O_CREAT, 0644);
// Does not fail if file exists; opens existing file insteadWhy this works
Without O_EXCL, O_CREAT opens an existing file rather than failing.
Linux Programmer Manual errno(3)
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev