← 都来码 / Dolaima← 例程索引objc/test/file_io.m原文

objc/test/file_io.m · 2321 字节 · 下载原文

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

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

//

// ⚠ **原版是一个 5 行桩,从来没有编过**:`asm("CALL shared_file_test")` 那一行里,

//   `shared_file_test` **在 `Lib/` 里根本不存在**(全库 grep 无命中)—— ObjC 确实支持 `asm`,

//   所以它报的不是"没有 asm",而是「未定义的函数 'shared_file_test'」(实测)。

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

// ⚠ **The original was a 5-line stub that never compiled**: `shared_file_test` does not exist

//   anywhere under `Lib/`. ObjC does support `asm`, so the error is "undefined function

//   'shared_file_test'" rather than "no asm". The same stub was copied into C# / R / Java / Swift.

//

// ⚠ `file.vml` 是 ObjC 的**自动链接库** ⇒ `fopen` 这些裸名由链接器解析。

// ⚠ `file.vml` is auto-linked for ObjC, so the linker resolves the bare names.

//

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

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


int main() {
    // 1) 只写打开(mode 1 = 建 + 截断),写 5 个字节

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

    int h = fopen("objc_file_io.txt", 1);
    if (h >= 0) {
        fwrite(h, "hello", 5);
        fclose(h);
        printf("WRITE=ok\n");
    } else {
        printf("WRITE=open-failed\n");
    }

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

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

    int h2 = fopen("objc_file_io.txt", 0);
    if (h2 >= 0) {
        char buf[6] = "     ";        // 5 格缓冲 + 结束符(ObjC 前端不吃空的 `[]`)

        fread(h2, buf, 5);
        fclose(h2);
        printf("CONTENT=%s\n", buf);
    } else {
        printf("CONTENT=reopen-failed\n");
    }
    return 0;
}
// 期望(与别的语言的 `file_io.*` 同一份判据):

// EXPECT: WRITE=ok

// EXPECT: CONTENT=hello