fopen(模式族:r/r+/w/w+/a/a+/x/x+)

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

按模式字符串打开文件——8 种模式决定「可读/可写、是否存在才允许、打开时是否截断、写入是否强制追加」四个语义维度,各语言打开文件的模式名各成体系。

C C23

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

int main(void) {
    // C 没有裸 'x':排他创建一族用 C11 的 '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");

        // 实验 A:文件已存在,内容为 "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 返回 0(写入被拒绝)
            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';
        }

        // 实验 B:文件不存在
        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;
}
输出
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 没有排他创建的 openmode,因此 x 一族走 C FILE API
    // 配 C11 的 "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_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");

        // 实验 A:文件已存在,内容为 "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';
        }

        // 实验 B:文件不存在
        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;
}
输出
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 风格模式 -> FileMode/FileAccess(跨语言映射);
// .NET 的 FileMode.Append 只能与 FileAccess.Write 搭配,因此 a+ 用
// OpenOrCreate + ReadWrite + 定位到末尾来模拟
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), // 模拟追加
    "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+" })
{
    // 实验 A:文件已存在,内容为 "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); // 模拟追加定位
            fs.WriteByte((byte)'X');
            writeState = "yes";
        }
        catch (NotSupportedException)
        {
            writeState = "no"; // 只读流
        }
    }
    catch (IOException)
    {
        // 打开被拒:对已存在文件用 x/x+
    }
    string result = File.ReadAllText(path);

    // 实验 B:文件不存在
    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+
    }
    File.Delete(path);

    Console.WriteLine($"{mode.PadRight(4)}open:{openState.PadRight(6)}write:{writeState.PadRight(4)}result:{result.PadRight(6)}missing:{missing}");
}
输出
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 风格模式 -> OpenFile flag 组合(跨语言映射)
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 {
		// 实验 A:文件已存在,内容为 "abc"
		os.WriteFile(path, []byte("abc"), 0644)
		openState, writeState := "FAIL", "-"
		if f, err := os.OpenFile(path, flagsFor(mode), 0644); err == nil {
			openState = "ok"
			// 对 O_RDONLY 句柄写入返回 EBADF(写入被拒绝)
			if _, werr := f.WriteString("X"); werr == nil {
				writeState = "yes"
			} else {
				writeState = "no"
			}
			f.Close()
		}
		data, _ := os.ReadFile(path)
		result := string(data)

		// 实验 B:文件不存在
		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)
	}
}
输出
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 风格模式 -> newOutputStream 选项(跨语言映射);
    // Java 没有「只读打开」的 OutputStream,因此 'r' 用 InputStream
    // (结构上就不可能写入)
    static List<StandardOpenOption> optionsFor(String mode) {
        return switch (mode) {
            case "r" -> List.of(StandardOpenOption.WRITE); // 占位;r 在下方单独分支
            case "r+" -> List.of(StandardOpenOption.WRITE); // 打开,不截断
            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+")) {
            // 实验 A:文件已存在,内容为 "abc"
            Files.writeString(path, "abc");
            String openState = "FAIL", writeState = "-";
            if (mode.equals("r")) {
                try (InputStream in = Files.newInputStream(path)) {
                    openState = "ok";
                    writeState = "no"; // InputStream 没有写通道
                } 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+
                }
            }
            String result = Files.readString(path);

            // 实验 B:文件不存在
            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+(x/x+ 走不到这里)
            }
            Files.deleteIfExists(path);

            System.out.printf("%-4sopen:%-6swrite:%-4sresult:%-6smissing:%s%n",
                    mode, openState, writeState, result, missing);
        }
    }
}
输出
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 的 flag 字符串是 fopen 模式的近亲:同样的字母,同样的语义——
// 但没有裸 'x',排他创建写作 'wx'/'wx+'
const nodeFlag = (m) => (m === "x" ? "wx" : m === "x+" ? "wx+" : m);
for (const mode of ["r", "r+", "w", "w+", "a", "a+", "x", "x+"]) {
  // 实验 A:文件已存在,内容为 "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"; // 只读 fd 拒绝写入
    }
  } catch {
    // 打开被拒:对已存在文件用 x
  } finally {
    if (fd !== null) fs.closeSync(fd);
  }
  const result = fs.readFileSync(path, "utf8");

  // 实验 B:文件不存在
  fs.rmSync(path, { force: true });
  let missing = "fail";
  let fd2 = null;
  try {
    fd2 = fs.openSync(path, nodeFlag(mode));
    missing = "create";
  } catch {
    // 文件不存在时的 r/r+
  } 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}`
  );
}
输出
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_');

// 模式串就是 fopen 的 API 本体:8 种模式,各管 4 个语义
foreach (['r', 'r+', 'w', 'w+', 'a', 'a+', 'x', 'x+'] as $mode) {
    // 实验 A:文件已存在,内容为 "abc"
    file_put_contents($path, 'abc');
    $openState = 'FAIL';
    $writeState = '-';
    if (is_resource($f = @fopen($path, $mode))) {
        $openState = 'ok';
        // 对只读流 fwrite 返回 0(写入被拒绝)
        $writeState = @fwrite($f, 'X') ? 'yes' : 'no';
        fclose($f);
    }
    $result = file_get_contents($path);

    // 实验 B:文件不存在
    @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);
输出
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 的 open() 直接沿用 fopen 的模式字母
for mode in ["r", "r+", "w", "w+", "a", "a+", "x", "x+"]:
    # 实验 A:文件已存在,内容为 "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 是 OSError 子类
            write_state = "no"
        finally:
            f.close()
    except OSError:
        pass  # 打开被拒:对已存在文件用 x
    with open(path) as f:
        result = f.read()

    # 实验 B:文件不存在
    if os.path.exists(path):
        os.unlink(path)
    missing = "fail"
    try:
        open(path, mode).close()
        missing = "create"
    except OSError:  # 文件不存在时的 r/r+
        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}")
输出
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 风格模式 -> OpenOptions builder(跨语言映射):
    // Rust 没有模式字母,只有布尔能力位
    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+"] {
        // 实验 A:文件已存在,内容为 "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();
            // 对只读文件写入返回错误(写入被拒绝)
            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();

        // 实验 B:文件不存在
        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
        );
    }
}
输出
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 的 flag 字符串是 fopen 模式的近亲:同样的字母,同样的语义——
// 但没有裸 'x',排他创建写作 '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+"]) {
  // 实验 A:文件已存在,内容为 "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"; // 只读 fd 拒绝写入
    }
  } catch {
    // 打开被拒:对已存在文件用 x
  } finally {
    if (fd !== null) fs.closeSync(fd);
  }
  const result = fs.readFileSync(path, "utf8");

  // 实验 B:文件不存在
  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+
  } 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}`
  );
}
输出
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

语言差异说明

统一结论(也是各语言 output 的那张表):r 族要求文件存在、不截断(r 只读、r+ 可读写、写入从头覆盖);w 族打开即截断为 0、不存在则创建(w 只写、w+ 可读写);a 族不存在则创建、写入强制追加到末尾、不截断(a 只写、a+ 可读可写但写仍在末尾);x 族排他创建——文件已存在直接失败、不存在才创建(x 只写、x+ 可读写),是「只创建一次」的原子操作。

C:fopen 模式串的祖师爷;没有裸 'x',排他创建是 C11 的 'wx'/'w+x' 后缀写法。

C++:std::fstream 的 openmode(in/out/app/trunc/binary)没有排他创建组合,x 一族走 C FILE API('wx')或 POSIX O_EXCL。

C#:FileMode(Open/OpenOrCreate/Create/CreateNew/Truncate/Append)× FileAccess(Read/Write/ReadWrite)两个枚举组合表达——但 FileMode.Append 只允许搭配 FileAccess.Write,a+(可读可追加)没有原生组合,需 OpenOrCreate + 定位到末尾模拟。

Go:os.OpenFile 用 flag 位组合(O_RDONLY/O_RDWR + O_CREATE/O_TRUNC/O_APPEND/O_EXCL),比模式字母更显式。

Java:Files.newOutputStream 用 StandardOpenOption 组合(WRITE/CREATE/TRUNCATE_EXISTING/APPEND/CREATE_NEW);没有「只读 OutputStream」概念,r 只能用 newInputStream(结构上无写通道)。

JavaScript:Node 的 flag 字符串与 fopen 几乎同名同义(r/r+/w/w+/a/a+/x/x+,另有 wx/wx+ 别名),是十门语言里迁移成本最低的。

PHP:模式串就是 fopen 的本体;'x' 是原生模式(源自 PHP 5);加 'b'(binary)或 't'(text,仅 Windows 有意义)后缀。

Python:open() 同样直接用 fopen 字母(含 'x');额外提供 'b' 二进制模式和 newline= 参数控制行尾转换。

Rust:没有模式字母——OpenOptions 用布尔能力位(read/write/create/truncate/append/create_new)显式拼装,语义一一对应但写法最长。

TypeScript:同 JS。