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

swift/test/file_io.swift · 2020 字节 · 下载原文

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

//

// ⚠ **原版是一个 5 行桩、从来没有能编过**:它写的是

//   `asm("CALL shared_file_test")` / `asm("LOAD R0 #100")` / `asm("SYSCALL 3")`,而

//   ① Swift 前端**有意移除了 `asm()`**(见 `SwiftCompiler/CodeGenerator.cs` 的 GenerateCall),

//   ② 它引用的 `shared_file_test` **在 `Lib/` 里根本不存在**(全库 grep 无命中)。

//   现在改成**走库**的写法 —— `Lib/swift/file.swift` 也一并从 `asm("SYSCALL nn")`

//   改成了"声明空壳"(与 GenLib 产出的 `vml_ui.swift` 同一形态)。

// ⚠ **不要 `#include` 那两个声明文件**:`vml_ui.swift` / `file.swift` 里的函数是**空壳**

//   (`return 0`),而链接器对**同名的程序内定义**会**遮蔽库实现** ⇒ 一旦包含,

//   `ui_store_set` 这类调用全变成**空操作**(实测:带 include 时 store 是空的、

//   去掉 include 立刻拿到 `{"vml.k":"v"}`)。库本身由 `builtins_swift.c` 的

//   `#param lib(...)` 自动挂进链接集,**不需要**这些声明文件。


// ⚠ **顶层语句就是程序体** —— Swift 前端不调 `func main()`(写了也没人调,

//   原版那个桩还有这第三个毛病)。

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

var h = fopen("swift_file_io.txt", 1)
if h >= 0 {      // ⚠ 句柄是 **0 起**的(第一个文件就是 0)—— `> 0` 会把成功判成失败


    fwrite(h, "hello", 5)
    fclose(h)
    ui_store_set("write", "ok")
} else {
    ui_store_set("write", "open-failed")
}

// 2) 只读打开(mode 0),读回来

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

    fread(h2, buf, 5)
    fclose(h2)
    ui_store_set("content", buf)            // 期望 "hello"

} else {
    ui_store_set("content", "reopen-failed")
}