EEXIST
Linux / POSIXERRORCommonFile SystemHIGH confidence

File Already Exists

What this means

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.

Why it happens
  1. 1Opening a file with O_CREAT | O_EXCL when the file already exists.
  2. 2Running mkdir for a directory that already exists.
  3. 3Creating a hard link to a path that already exists.
  4. 4A race condition where two processes try to create the same file simultaneously.
How to reproduce

Creating a directory that already exists.

trigger — this will error
trigger — this will error
$ 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

Use mkdir -p to create directories idempotently
$ 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

Use O_CREAT without O_EXCL to open-or-create a file
int fd = open("/tmp/myfile", O_RDWR | O_CREAT, 0644);
// Does not fail if file exists; opens existing file instead

Why this works

Without O_EXCL, O_CREAT opens an existing file rather than failing.

Sources
Official documentation ↗

Linux Programmer Manual errno(3)

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Linux / POSIX errors