← 都来码 / Dolaima← 例程索引csharp/test/file_io.cs原文

csharp/test/file_io.cs · 3030 字节 · 下载原文

// file_io.cs —— 文件读写示例(走 `Lib/shared/src/file.c` 的库实现)

// file_io.cs — file read/write demo (going through the library in `Lib/shared/src/file.c`)

//

// ⚠ **原版是一个 5 行桩,从来没有编过**:三行 `asm("…")`,而 C# 前端**没有 `asm`**

//   (报「未定义的函数 'asm'」,实测),它引用的 `shared_file_test` 在 `Lib/` 里也不存在。

//   同一个桩还抄在 ObjC / R / Java / Swift 那几门里(Swift 与 Java 已先改好)。

// ⚠ **The original was a 5-line stub that never compiled**: three `asm("…")` lines, and the C#

//   frontend has no `asm` at all (measured: "undefined function 'asm'"), while `shared_file_test`

//   does not exist under `Lib/` either. The same stub was copied into ObjC / R / Java / Swift.

//

// ⚠ `file.vml` 是 C# 的**自动链接库**(`Lib/csharp/builtin.vml` 里有 `.linked "file.vml"`)

//   ⇒ `fopen` 这些裸名由链接器解析,**不需要**任何声明文件。

// ⚠ `file.vml` is auto-linked for C# (see `.linked "file.vml"` in `Lib/csharp/builtin.vml`),

//   so the linker resolves the bare names — no declaration file needed.

//

// ⚠ **句柄是 0 起的**(第一个文件就是 0)—— 写成 `> 0` 会把成功判成失败。

// ⚠ **Handles start at 0** (the first open file is 0), so `> 0` would read success as failure.


class FileIO {
    static void Main() {
        // 1) 只写打开(mode 1 = 建 + 截断),写 5 个字节

        // 1) Open for writing (mode 1 = create + truncate) and write 5 bytes

        int h = fopen("csharp_file_io.txt", 1);
        if (h >= 0) {
            fwrite(h, "hello", 5);
            fclose(h);
            Console.WriteLine("WRITE=ok");
        } else {
            Console.WriteLine("WRITE=open-failed");
        }

        // 2) 只读打开(mode 0),读回来 —— 这一半才是"写进去的到底是不是那 5 个字节"

        // 2) Open for reading (mode 0) and read it back — this half proves the bytes landed

        int h2 = fopen("csharp_file_io.txt", 0);
        if (h2 >= 0) {
            string buf = "     ";          // 5 格缓冲(数据段里的可写串)

            fread(h2, buf, 5);
            fclose(h2);
            // ⚠ **别写 `"CONTENT=" + buf`** —— C# 前端的 `+` 不做字符串拼接,

            //   实测打出的是地址(`79161`)。标签与值**分两行打**。

            // ⚠ **Do not write `"CONTENT=" + buf`**: the C# frontend's `+` does not concatenate

            //   strings (measured: it prints the address, `79161`). Print label and value separately.

            Console.WriteLine("CONTENT=");
            Console.WriteLine(buf);
        } else {
            Console.WriteLine("CONTENT=reopen-failed");
        }
    }
}
// 期望(与别的语言的 `file_io.*` 同一份判据;本门拼不了串 ⇒ 标签与值分两行):

// EXPECT: WRITE=ok

// EXPECT: CONTENT=

// EXPECT: hello