r/test/file_io.r · 3284 字节 · 下载原文
# file_io.r —— 文件读写示例(走 `Lib/shared/src/file.c` 的库实现)
# file_io.r — file read/write demo (going through the library in `Lib/shared/src/file.c`)
#
# ⚠ **原版是一个 5 行桩,从来没有编过**:三行 `asm("…")`,而 R 前端**没有 `asm`**
# (报「未定义的函数 'func_asm'」,实测),它引用的 `shared_file_test` 在 `Lib/` 里也不存在。
# 同一个桩还抄在 C# / ObjC / Java / Swift 那几门里(Swift 与 Java 已先改好)。
# ⚠ **The original was a 5-line stub that never compiled**: three `asm("…")` lines, and the R
# frontend has no `asm` (measured: "undefined function 'func_asm'"), while `shared_file_test`
# does not exist under `Lib/` either. The same stub was copied into C# / ObjC / Java / Swift.
#
# ⚠ `file.vml` 是 R 的**自动链接库**(`Lib/r/builtin.vml` 里有 `.linked "file.vml"`)
# ⇒ `fopen` 这些裸名由链接器解析,**不需要**任何声明文件。
# ⚠ `file.vml` is auto-linked for R (see `.linked "file.vml"` in `Lib/r/builtin.vml`).
#
# ⚠ **句柄是 0 起的**(第一个文件就是 0)—— 写成 `> 0` 会把成功判成失败。
# ⚠ **Handles start at 0** (the first open file is 0), so `> 0` would read success as failure.
# 1) 只写打开(mode 1 = 建 + 截断),写 5 个字节
# 1) Open for writing (mode 1 = create + truncate) and write 5 bytes
h <- fopen("r_file_io.txt", 1)
if (h >= 0) {
fwrite(h, "hello", 5)
fclose(h)
cat("WRITE=ok\n")
} else {
cat("WRITE=open-failed\n")
}
# 2) 只读打开(mode 0),读回来 —— 这一半才是"写进去的到底是不是那 5 个字节"
# 2) Open for reading (mode 0) and read it back — this half proves the bytes landed
# ⚠ `cat` 要**一次一个实参**(见 `Examples/r/demo_std.r` 的注记)。
# ⚠ `cat` takes **one argument per call** (see the note in `Examples/r/demo_std.r`).
h2 <- fopen("r_file_io.txt", 0)
if (h2 >= 0) {
buf <- " " # 5 格缓冲(数据段里的可写串)
fread(h2, buf, 5)
fclose(h2)
# ⚠ **读回来的内容在这里只能用"数字"验**:R 前端的 `cat` 打**字符串变量**打的是地址
# (实测 `s <- "str"; cat(s)` 打出 `1035`),只有**字面量**才按文字打。
# `strcmp` 返 0 = 两份一致,`strlen` 自己告诉你读到了几个字节 —— 两条都真的证明
# "写进去的 5 个字节落在缓冲区里了",而且都是数字,能打出来。
# ⚠ **The read-back can only be checked numerically here**: this frontend's `cat` prints the
# *address* for a string variable (measured: `s <- "str"; cat(s)` prints `1035`); only literals
# print as text. `strcmp` returning 0 and `strlen` returning 5 both prove the 5 bytes landed.
cat("MATCH=")
cat(strcmp(buf, "hello")) # 0 = 与 "hello" 逐字节相同
cat("\n")
cat("LEN=")
cat(strlen(buf)) # 5 = 读到的字节数
cat("\n")
} else {
cat("MATCH=reopen-failed\n")
cat("LEN=0\n")
}
# 期望(与别的语言的 `file_io.*` 同一份判据;本门读回来只能数字验,见上):
# EXPECT: WRITE=ok
# EXPECT: MATCH=0
# EXPECT: LEN=5