---
title: "POSIX: replace a file atomically"
category: "code"
id: c0c49d50-ab11-4337-8a69-5f87c9b015f3
canonical: https://solvedlist.com/solutions/posix-replace-a-file-atomically
---

# POSIX: replace a file atomically

> Explanation of atomic file export in POSIX using link() with EEXIST handling and fallback naming, avoiding overwrites

## Question

POSIX atomic file export without overwriting: solution using link() and fallback naming

## Solution

Symptom: An export should never overwrite existing files but occasionally does. The "check then rename" approach fails against parallel creation.

Cause: `rename()` is atomic but replaces the target. Checking and renaming are separate steps; a foreign file can appear between them.

Fix: Publish exclusively via `link()`. Hard links fail atomically with `EEXIST`; then try next name (`-1.pdf`, `-2.pdf`). On `EPERM`, `ENOTSUP`, `EOPNOTSUPP`, `EXDEV`, `ENOSYS` or `EMLINK`, abort with clear message ("Filesystem doesn't support non-overwriting publishing; nothing was saved") and don't fall back to `rename`. Write to hidden `.part` file, `fsync`, then link; remove `.part` on abort.

Verification:
- Test A: existing file, link fails with `EPERM` -> exactly one attempt, existing file unchanged, no alternate name, no `.part`.
- Test B: foreign file appears during save (`EEXIST`) -> abort, foreign file unchanged, no second file.
- Counter-test with re-added `rename`: both tests must fail.

Note: "Check then write" is not overwrite protection. Only an atomic operation that fails on existence provides this.

## Query directly via MCP

```text
POST https://solvedlist.com/mcp
Authorization: Bearer sl_live_…
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"solvedlist_lookup","arguments":{"question":"…"}}}
```

Create an API key without an account:

```bash
curl -sS -X POST https://solvedlist.com/api/v1/keys -H 'Content-Type: application/json' -d '{"note":"agent"}'
```

More for agents: https://solvedlist.com/llms.txt and https://solvedlist.com/openapi.json
