fopen (mode family: r/r+/w/w+/a/a+/x/x+)

fopen(string $filename, string $mode): resource|false

Opens a file per a mode string — the 8 modes decide four semantics (read/write, existence policy, truncate-on-open, forced-append); every language has its own open-mode vocabulary.

C C23

C23
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(void) {
    // C has no bare 'x': the exclusive-create family uses C11's 'wx'/'w+x'
    const char *modes[] = {"r", "r+", "w", "w+", "a", "a+", "wx", "w+x"};
    const char *labels[] = {"r", "r+", "w", "w+", "a", "a+", "x", "x+"};
    const char *path = "/tmp/fmodes_c_demo.dat";

    for (int i = 0; i < 8; i++) {
        char result[16];
        const char *open_state = "FAIL", *write_state = "-";
        strcpy(result, "abc");

        // experiment A: the file already exists with content "abc"
        FILE *init = fopen(path, "wb");
        fwrite("abc", 1, 3, init);
        fclose(init);

        FILE *f = fopen(path, modes[i]);
        if (f) {
            open_state = "ok";
            // fwrite to a read-only stream returns 0 (write refused)
            write_state = fwrite("X", 1, 1, f) == 1 ? "yes" : "no";
            fclose(f);
            FILE *r = fopen(path, "rb");
            size_t n = fread(result, 1, sizeof(result) - 1, r);
            fclose(r);
            result[n] = '\0';
        }

        // experiment B: the file does not exist
        unlink(path);
        const char *missing = "fail";
        FILE *f2 = fopen(path, modes[i]);
        if (f2) {
            missing = "create";
            fclose(f2);
        }
        unlink(path);

        printf("%-4sopen:%-6swrite:%-4sresult:%-6smissing:%s\n",
               labels[i], open_state, write_state, result, missing);
    }
    return 0;
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <string>
#include <unistd.h>

int main() {
    // std::fstream has no exclusive-create openmode, so the x family goes
    // through the C FILE API with C11's "wx"/"w+x" strings
    const char* modes[] = {"r", "r+", "w", "w+", "a", "a+", "wx", "w+x"};
    const char* labels[] = {"r", "r+", "w", "w+", "a", "a+", "x", "x+"};
    const char* path = "/tmp/fmodes_cpp_demo.dat";

    for (int i = 0; i < 8; i++) {
        char result[16];
        const char* open_state = "FAIL";
        const char* write_state = "-";
        std::strcpy(result, "abc");

        // experiment A: the file already exists with content "abc"
        FILE* init = std::fopen(path, "wb");
        std::fwrite("abc", 1, 3, init);
        std::fclose(init);

        FILE* f = std::fopen(path, modes[i]);
        if (f) {
            open_state = "ok";
            write_state = std::fwrite("X", 1, 1, f) == 1 ? "yes" : "no";
            std::fclose(f);
            FILE* r = std::fopen(path, "rb");
            size_t n = std::fread(result, 1, sizeof(result) - 1, r);
            std::fclose(r);
            result[n] = '\0';
        }

        // experiment B: the file does not exist
        unlink(path);
        const char* missing = "fail";
        FILE* f2 = std::fopen(path, modes[i]);
        if (f2) {
            missing = "create";
            std::fclose(f2);
        }
        unlink(path);

        std::printf("%-4sopen:%-6swrite:%-4sresult:%-6smissing:%s\n",
                    labels[i], open_state, write_state, result, missing);
    }
    return 0;
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

C# v11.0.100

v11.0.100
using System.IO;

// fopen-style mode -> FileMode/FileAccess (the cross-language mapping);
// .NET's FileMode.Append only pairs with FileAccess.Write, so a+ is emulated
// with OpenOrCreate + ReadWrite + seek-to-end
static (FileMode Mode, FileAccess Access) optionsFor(string mode) => mode switch
{
    "r" => (FileMode.Open, FileAccess.Read),
    "r+" => (FileMode.Open, FileAccess.ReadWrite),
    "w" => (FileMode.Create, FileAccess.Write),
    "w+" => (FileMode.Create, FileAccess.ReadWrite),
    "a" => (FileMode.Append, FileAccess.Write),
    "a+" => (FileMode.OpenOrCreate, FileAccess.ReadWrite), // emulated append
    "x" => (FileMode.CreateNew, FileAccess.Write),
    _ => (FileMode.CreateNew, FileAccess.ReadWrite), // x+
};

string path = "/tmp/fmodes_cs_demo.dat";
foreach (var mode in new[] { "r", "r+", "w", "w+", "a", "a+", "x", "x+" })
{
    // experiment A: the file already exists with content "abc"
    File.WriteAllText(path, "abc");
    string openState = "FAIL", writeState = "-";
    try
    {
        var (fileMode, access) = optionsFor(mode);
        using var fs = new FileStream(path, fileMode, access);
        openState = "ok";
        try
        {
            if (mode == "a+") fs.Seek(0, SeekOrigin.End); // emulate append positioning
            fs.WriteByte((byte)'X');
            writeState = "yes";
        }
        catch (NotSupportedException)
        {
            writeState = "no"; // read-only stream
        }
    }
    catch (IOException)
    {
        // open refused: x/x+ on an existing file
    }
    string result = File.ReadAllText(path);

    // experiment B: the file does not exist
    File.Delete(path);
    string missing = "fail";
    try
    {
        var (fileMode2, access2) = optionsFor(mode);
        using var fs2 = new FileStream(path, fileMode2, access2);
        missing = "create";
    }
    catch (IOException)
    {
        // r/r+ on a missing file
    }
    File.Delete(path);

    Console.WriteLine($"{mode.PadRight(4)}open:{openState.PadRight(6)}write:{writeState.PadRight(4)}result:{result.PadRight(6)}missing:{missing}");
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
)

// fopen-style mode -> OpenFile flag composition (the cross-language mapping)
func flagsFor(mode string) int {
	switch mode {
	case "r":
		return os.O_RDONLY
	case "r+":
		return os.O_RDWR
	case "w":
		return os.O_WRONLY | os.O_CREATE | os.O_TRUNC
	case "w+":
		return os.O_RDWR | os.O_CREATE | os.O_TRUNC
	case "a":
		return os.O_WRONLY | os.O_CREATE | os.O_APPEND
	case "a+":
		return os.O_RDWR | os.O_CREATE | os.O_APPEND
	case "x":
		return os.O_WRONLY | os.O_CREATE | os.O_EXCL
	default: // "x+"
		return os.O_RDWR | os.O_CREATE | os.O_EXCL
	}
}

func main() {
	modes := []string{"r", "r+", "w", "w+", "a", "a+", "x", "x+"}
	path := "/tmp/fmodes_go_demo.dat"

	for _, mode := range modes {
		// experiment A: the file already exists with content "abc"
		os.WriteFile(path, []byte("abc"), 0644)
		openState, writeState := "FAIL", "-"
		if f, err := os.OpenFile(path, flagsFor(mode), 0644); err == nil {
			openState = "ok"
			// writing to an O_RDONLY handle returns EBADF (write refused)
			if _, werr := f.WriteString("X"); werr == nil {
				writeState = "yes"
			} else {
				writeState = "no"
			}
			f.Close()
		}
		data, _ := os.ReadFile(path)
		result := string(data)

		// experiment B: the file does not exist
		os.Remove(path)
		missing := "fail"
		if f2, err2 := os.OpenFile(path, flagsFor(mode), 0644); err2 == nil {
			missing = "create"
			f2.Close()
		}
		os.Remove(path)

		fmt.Printf("%-4sopen:%-6swrite:%-4sresult:%-6smissing:%s\n",
			mode, openState, writeState, result, missing)
	}
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

Java v27.0.1

v27.0.1
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class Main {
    // fopen-style mode -> newOutputStream options (the cross-language mapping);
    // Java has no single "open read-only" OutputStream, so 'r' uses an
    // InputStream (write impossible by construction)
    static List<StandardOpenOption> optionsFor(String mode) {
        return switch (mode) {
            case "r" -> List.of(StandardOpenOption.WRITE); // placeholder; r branches below
            case "r+" -> List.of(StandardOpenOption.WRITE); // open, no truncate
            case "w", "w+" -> List.of(StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            case "a", "a+" -> List.of(StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            default -> List.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); // x, x+
        };
    }

    public static void main(String[] args) throws Exception {
        Path path = Path.of("/tmp/fmodes_java_demo.dat");
        for (String mode : List.of("r", "r+", "w", "w+", "a", "a+", "x", "x+")) {
            // experiment A: the file already exists with content "abc"
            Files.writeString(path, "abc");
            String openState = "FAIL", writeState = "-";
            if (mode.equals("r")) {
                try (InputStream in = Files.newInputStream(path)) {
                    openState = "ok";
                    writeState = "no"; // InputStream has no write channel
                } catch (Exception e) {
                    openState = "FAIL";
                }
            } else {
                try (OutputStream out = Files.newOutputStream(path,
                        optionsFor(mode).toArray(new StandardOpenOption[0]))) {
                    openState = "ok";
                    out.write('X');
                    writeState = "yes";
                } catch (Exception e) {
                    openState = "FAIL"; // x/x+ on an existing file
                }
            }
            String result = Files.readString(path);

            // experiment B: the file does not exist
            Files.deleteIfExists(path);
            String missing = "fail";
            try (OutputStream out = Files.newOutputStream(path,
                    optionsFor(mode).toArray(new StandardOpenOption[0]))) {
                missing = "create";
            } catch (Exception e) {
                missing = "fail"; // r/r+ (and x/x+ never hit here)
            }
            Files.deleteIfExists(path);

            System.out.printf("%-4sopen:%-6swrite:%-4sresult:%-6smissing:%s%n",
                    mode, openState, writeState, result, missing);
        }
    }
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

JavaScript v26.13.1

v26.13.1
const fs = require("fs");
const path = "/tmp/fmodes_js_demo.dat";

// Node's flag strings are the closest cousin of fopen's modes:
// same letters, same semantics — but there is no bare 'x', exclusive-create
// is spelled 'wx'/'wx+'
const nodeFlag = (m) => (m === "x" ? "wx" : m === "x+" ? "wx+" : m);
for (const mode of ["r", "r+", "w", "w+", "a", "a+", "x", "x+"]) {
  // experiment A: the file already exists with content "abc"
  fs.writeFileSync(path, "abc");
  let openState = "FAIL", writeState = "-";
  let fd = null;
  try {
    fd = fs.openSync(path, nodeFlag(mode));
    openState = "ok";
    try {
      fs.writeSync(fd, "X");
      writeState = "yes";
    } catch {
      writeState = "no"; // read-only fd refuses writes
    }
  } catch {
    // open refused: x on an existing file
  } finally {
    if (fd !== null) fs.closeSync(fd);
  }
  const result = fs.readFileSync(path, "utf8");

  // experiment B: the file does not exist
  fs.rmSync(path, { force: true });
  let missing = "fail";
  let fd2 = null;
  try {
    fd2 = fs.openSync(path, nodeFlag(mode));
    missing = "create";
  } catch {
    // r/r+ on a missing file
  } finally {
    if (fd2 !== null) fs.closeSync(fd2);
  }
  fs.rmSync(path, { force: true });

  console.log(
    `${mode.padEnd(4)}open:${openState.padEnd(6)}write:${writeState.padEnd(4)}result:${result.padEnd(6)}missing:${missing}`
  );
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

PHP v8.6.0

v8.6.0
$path = tempnam(sys_get_temp_dir(), 'fm_');

// the mode string IS the fopen API: 8 modes, four semantics each
foreach (['r', 'r+', 'w', 'w+', 'a', 'a+', 'x', 'x+'] as $mode) {
    // experiment A: the file already exists with content "abc"
    file_put_contents($path, 'abc');
    $openState = 'FAIL';
    $writeState = '-';
    if (is_resource($f = @fopen($path, $mode))) {
        $openState = 'ok';
        // fwrite to a read-only stream returns 0 (write refused)
        $writeState = @fwrite($f, 'X') ? 'yes' : 'no';
        fclose($f);
    }
    $result = file_get_contents($path);

    // experiment B: the file does not exist
    @unlink($path);
    $missing = 'fail';
    if (is_resource($f = @fopen($path, $mode))) {
        $missing = 'create';
        fclose($f);
    }
    @unlink($path);

    printf("%-4sopen:%-6swrite:%-4sresult:%-6smissing:%s\n",
        $mode, $openState, $writeState, $result, $missing);
}
unlink($path);
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

Python v3.15.2

v3.15.2
import os

path = "/tmp/fmodes_py_demo.dat"

# Python's open() shares fopen's mode letters directly
for mode in ["r", "r+", "w", "w+", "a", "a+", "x", "x+"]:
    # experiment A: the file already exists with content "abc"
    with open(path, "w") as f:
        f.write("abc")
    open_state, write_state = "FAIL", "-"
    try:
        f = open(path, mode)
        open_state = "ok"
        try:
            f.write("X")
            write_state = "yes"
        except OSError:  # io.UnsupportedOperation subclasses OSError
            write_state = "no"
        finally:
            f.close()
    except OSError:
        pass  # open refused: x on an existing file
    with open(path) as f:
        result = f.read()

    # experiment B: the file does not exist
    if os.path.exists(path):
        os.unlink(path)
    missing = "fail"
    try:
        open(path, mode).close()
        missing = "create"
    except OSError:  # r/r+ on a missing file
        pass
    if os.path.exists(path):
        os.unlink(path)

    print(f"{mode:<4}open:{open_state:<6}write:{write_state:<4}result:{result:<6}missing:{missing}")
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

Rust v1.99.1

v1.99.1
use std::fs::{self, OpenOptions};
use std::io::Write;

fn main() {
    let path = std::path::Path::new("/tmp/fmodes_rs_demo.dat");

    // fopen-style mode -> OpenOptions builder (the cross-language mapping):
    // Rust has no mode letters, just boolean capabilities
    let opts = |m: &str| {
        let mut o = OpenOptions::new();
        match m {
            "r" => {
                o.read(true);
            }
            "r+" => {
                o.read(true).write(true);
            }
            "w" => {
                o.write(true).create(true).truncate(true);
            }
            "w+" => {
                o.read(true).write(true).create(true).truncate(true);
            }
            "a" => {
                o.write(true).create(true).append(true);
            }
            "a+" => {
                o.read(true).create(true).append(true);
            }
            "x" => {
                o.write(true).create_new(true);
            }
            _ => {
                o.read(true).write(true).create_new(true); // x+
            }
        }
        o
    };

    for mode in ["r", "r+", "w", "w+", "a", "a+", "x", "x+"] {
        // experiment A: the file already exists with content "abc"
        fs::write(path, "abc").unwrap();
        let mut open_state = "FAIL".to_string();
        let mut write_state = "-".to_string();
        if let Ok(mut f) = opts(mode).open(path) {
            open_state = "ok".to_string();
            // writing to a read-only file returns an error (write refused)
            write_state = match f.write_all(b"X") {
                Ok(()) => "yes".to_string(),
                Err(_) => "no".to_string(),
            };
        }
        let result = fs::read_to_string(path).unwrap_or_default();

        // experiment B: the file does not exist
        let _ = fs::remove_file(path);
        let mut missing = "fail".to_string();
        if opts(mode).open(path).is_ok() {
            missing = "create".to_string();
        }
        let _ = fs::remove_file(path);

        println!(
            "{:<4}open:{:<6}write:{:<4}result:{:<6}missing:{}",
            mode, open_state, write_state, result, missing
        );
    }
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

TypeScript v26.13.1

v26.13.1
import * as fs from "fs";

const path = "/tmp/fmodes_ts_demo.dat";

// Node's flag strings are the closest cousin of fopen's modes:
// same letters, same semantics — but there is no bare 'x', exclusive-create
// is spelled 'wx'/'wx+'
const nodeFlag = (m: string): string => (m === "x" ? "wx" : m === "x+" ? "wx+" : m);
for (const mode of ["r", "r+", "w", "w+", "a", "a+", "x", "x+"]) {
  // experiment A: the file already exists with content "abc"
  fs.writeFileSync(path, "abc");
  let openState = "FAIL", writeState = "-";
  let fd: number | null = null;
  try {
    fd = fs.openSync(path, nodeFlag(mode));
    openState = "ok";
    try {
      fs.writeSync(fd, "X");
      writeState = "yes";
    } catch {
      writeState = "no"; // read-only fd refuses writes
    }
  } catch {
    // open refused: x on an existing file
  } finally {
    if (fd !== null) fs.closeSync(fd);
  }
  const result = fs.readFileSync(path, "utf8");

  // experiment B: the file does not exist
  fs.rmSync(path, { force: true });
  let missing = "fail";
  let fd2: number | null = null;
  try {
    fd2 = fs.openSync(path, nodeFlag(mode));
    missing = "create";
  } catch {
    // r/r+ on a missing file
  } finally {
    if (fd2 !== null) fs.closeSync(fd2);
  }
  fs.rmSync(path, { force: true });

  console.log(
    `${mode.padEnd(4)}open:${openState.padEnd(6)}write:${writeState.padEnd(4)}result:${result.padEnd(6)}missing:${missing}`
  );
}
Output
r   open:ok    write:no  result:abc   missing:fail
r+  open:ok    write:yes result:Xbc   missing:fail
w   open:ok    write:yes result:X     missing:create
w+  open:ok    write:yes result:X     missing:create
a   open:ok    write:yes result:abcX  missing:create
a+  open:ok    write:yes result:abcX  missing:create
x   open:FAIL  write:-   result:abc   missing:create
x+  open:FAIL  write:-   result:abc   missing:create

Language differences

Unified conclusion (the table every language's output prints): r family requires the file to exist and never truncates (r read-only, r+ read-write, writes overwrite from the start); w family truncates to zero on open and creates when missing (w write-only, w+ read-write); a family creates when missing, forces writes to the end, never truncates (a write-only, a+ readable but writes still append); x family is exclusive create — fails outright if the file exists, creates only when missing (x write-only, x+ read-write), i.e. an atomic create-once.

C: the ancestor of fopen mode strings; there is no bare 'x' — exclusive create is C11's 'wx'/'w+x' suffix notation.

C++: std::fstream openmodes (in/out/app/trunc/binary) have no exclusive-create combination; the x family goes through the C FILE API ('wx') or POSIX O_EXCL.

C#: expressed as the FileMode (Open/OpenOrCreate/Create/CreateNew/Truncate/Append) × FileAccess (Read/Write/ReadWrite) matrix — but FileMode.Append only pairs with FileAccess.Write, so a+ (read + append) has no native combination and must be emulated with OpenOrCreate + seek-to-end.

Go: os.OpenFile composes flag bits (O_RDONLY/O_RDWR + O_CREATE/O_TRUNC/O_APPEND/O_EXCL) — more explicit than mode letters.

Java: Files.newOutputStream composes StandardOpenOptions (WRITE/CREATE/TRUNCATE_EXISTING/APPEND/CREATE_NEW); there is no read-only OutputStream concept, so 'r' must use newInputStream (structurally write-less).

JavaScript: Node's flag strings are nearly identical to fopen's (r/r+/w/w+/a/a+/x/x+, plus wx/wx+ aliases) — the lowest migration cost of the ten languages.

PHP: the mode string IS fopen; 'x' is a native mode (since PHP 5); add 'b' (binary) or 't' (text, Windows-only) suffixes as needed.

Python: open() uses the same fopen letters (including 'x'); additionally offers 'b' binary mode and a newline= parameter for line-ending translation.

Rust: no mode letters — OpenOptions assembles boolean capability bits (read/write/create/truncate/append/create_new), a one-to-one semantic match but the longest spelling.

TypeScript: same as JS.