Create a file without replacing existing data.
Create a file without replacing existing data in a complete Rust program using the standard library.
use std::fs;
use std::fs::OpenOptions;
fn main() -> Result<(), Box<dyn std::error::Error>> {
fs::write("important.txt", "keep")?;
let result = OpenOptions::new().write(true).create_new(true).open("important.txt");
println!("{}", result.unwrap_err().kind() == std::io::ErrorKind::AlreadyExists);
Ok(())
}
Expected output EXAMPLE
true
Details
Save as main.rs, compile with rustc --edition=2024 main.rs -o snippet, then run ./snippet. Uses only the Rust standard library. Work in a scratch directory for file examples.
Tested on Ubuntu 24.04.3 LTS · · rustc 1.99.1 (58cf8f9c3 2026-10-13) · Rust standard library
Test inputs, results and environment
The exact published code ran in a dedicated Linux test container with prepared inputs. Dedicated test container, external networking disabled, read-only root, temporary per-example working directory. Browser network requests are blocked. Fixtures and output records are isolated from the application database. Testing covers this example and its stated checks, not every input, operating system, or runtime version. The Linux container shares its host's kernel; this is not a native Windows test.
- Architecture / host kernel
- x86_64 / 6.18.54.1-microsoft-standard-WSL2
- Snippet identity / locale
- uid=65534, gid=65534 (unprivileged) / C.UTF-8
- Interpreter invocation
rustc --edition=2024 -D warnings main.rs -o snippet && ./snippet- Container image ID
sha256:c9bce90110f636fe04907469a37e9c8ac888171fd569cbf87101743ec7cdf099- Code SHA-256
1cdb88d202954933b854e14d0d679e5bc17c0f2689f54471e325d19ad2847fcd- Dependencies
- Rust standard library
Test input setup
These are the prepared inputs used by the test harness. See Details above for the prerequisites and how to run this example.
# No input files required.
Observed standard output
true
Exit code: 0. Standard error: empty. Validation: Exact stdout comparison. System-dependent values above are one recorded run.
Additional assertions that passed
Checks recorded by the test harness. Where Python assertions are shown, browser cases use Playwright and simulator cases may inspect pin transitions: result.stdout is captured output, work is the temporary directory, and Path is pathlib.Path. The harness also imports json and csv.
Exact stdout comparison; process returned zero without stderr.