Ruby 文件的输入与输出(I/O)
系统讲解 Ruby Kernel/IO 标准输入输出方法、File.new 与 File.open 块管理与打开模式、sysread/syswrite/each_byte/readlines/foreach、权限掩码、文件查询、Dir 目录操作及临时文件创建。
学完这一章,你能够
- 系统讲解 Ruby Kernel/IO 标准输入输出方法、File.new 与 File.open 块管理与打开模式、sysread/syswrite/each_byte/readlines/foreach、权限掩码、文件查询、Dir 目录操作及临时文件创建。
标准输入输出:puts、gets、putc 与 print
Ruby 的全部输入输出能力根植于 `IO` 类,并在 `Kernel` 模块中暴露了一组便捷顶层方法(如 `puts`、`print`、`gets`、`putc`、`printf` 等)。其中 `puts` 会输出变量或字符串并在每项末尾自动追加换行符,适合按行打印结果。
`gets` 从标准输入 `STDIN` 读取一整行文本(保留末尾换行符,常配合 `chomp` 去除);`putc` 与 `puts` 不同,它每次仅输出单个字符(传入字符串 `"Hello Ruby!"` 时只输出首字符 `H`);`print` 则输出整个字符串但不会自动换行,连续两次 `print` 会紧贴在同一行输出。
打开与关闭文件及打开模式
操作磁盘文件使用 `IO` 的子类 `File`。`File.new("filename", "mode")` 创建文件对象后必须显式调用 `close` 释放描述符;而 `File.open("filename", "mode") do |f| ... end` 支持关联代码块,无论块正常结束还是抛出异常都会自动关闭文件,是生产代码首选。常用 6 种文件模式(`r`、`r+`、`w`、`w+`、`a`、`a+`)见下表。
底层与逐行读写:sysread、syswrite、each_byte、readlines 与 foreach
所有 `IO` 基础方法都可直接作用于 `File` 实例(如 `aFile.gets`)。若需按字节执行无缓冲底层读写,可使用 `sysread(n)` 与 `syswrite(str)`:例如对文本文件调用 `sysread(20)` 会读取前 20 字节并将文件指针停在第 21 字节处;以 `r+` 模式调用 `syswrite("ABCDEF")` 则从当前位置覆写前 6 字节。注意不要将 `sysread`/`syswrite` 与带缓冲的 `gets`/`puts` 混用于同一句柄。
按字节迭代可使用 `aFile.rewind` 将指针复位后调用 `each_byte`(配合 `putc ch; putc ?.` 可逐字节输出);按行读取时,`IO.readlines("input.txt")` 会一次性将所有行读入数组,`IO.foreach("input.txt") { |line| ... }` 则逐行交给块处理而不在内存中缓存整份文件,处理大文件时内存更省。
重命名、删除、权限掩码与文件元数据查询
文件改名与删除分别使用 `File.rename(old, new)` 和 `File.delete(path)`(注意源示例文本中 `test2.txt` 与 `text2.txt` 拼写需保持一致)。调整 Unix 文件权限使用 `chmod` 并传入八进制掩码(如 `0755`),完整权限位掩码表见下文。
打开或处理文件前可用一组查询方法校验元信息:`File.exist?`(注意历史别名 `File.exists?` 已在 Ruby 3.2 移除,请统一使用 `File.exist?`)、`File.file?`、`File.directory?`、`File.readable?`/`writable?`/`executable?`、`File.zero?`、`File.size?`(空文件返回 `nil`,非空返回字节数)、`File.ftype`(返回 `file`、`directory`、`characterSpecial`、`blockSpecial`、`fifo`、`link`、`socket` 或 `unknown`)以及 `ctime`/`mtime`/`atime` 时间戳。
目录管理、临时文件与内建类参考
目录操作由 `Dir` 类负责:`Dir.chdir` 切换当前工作目录,`Dir.pwd` 查看当前路径;`Dir.entries` 返回目录项数组,`Dir.foreach` 逐项迭代,`Dir["/path/*"]` 支持通配符筛选;`Dir.mkdir` 创建目录(设置 Unix 权限时须写八进制 `0755`,而非十进制 `755`),`Dir.delete`/`Dir.unlink`/`Dir.rmdir` 用于删除空目录。
处理临时文件时,可引入标准库 `require 'tmpdir'` 后结合 `File.join(Dir.tmpdir, name)` 跨平台构造路径并在用完后删除;更稳妥的做法是引入 `require 'tempfile'` 使用 `Tempfile.new('prefix')`,它会自动生成防冲突路径并在对象关闭清理(`close!` / `unlink`)时安全回收。完整的 `File` 与 `Dir` 类及实例方法清单将在随后两章详细展开。
Ruby File 打开模式对照表
| 模式 | 说明 |
| r | 只读模式(默认),文件指针位于开头,文件不存在时报错。 |
| r+ | 读写模式,文件指针位于开头,不清空原内容。 |
| w | 只写模式;若文件已存在则截断覆写,不存在则新建。 |
| w+ | 读写模式;若文件已存在则截断覆写,不存在则新建。 |
| a | 追加只写模式;文件指针位于末尾,不存在则新建。 |
| a+ | 追加读写模式;写入始终追加到末尾,不存在则新建。 |
Ruby File#chmod 权限掩码表
| 八进制掩码 | 权限含义 |
| 0700 | 所有者可读、可写、可执行(rwx)。 |
| 0400 | 所有者可读(r)。 |
| 0200 | 所有者可写(w)。 |
| 0100 | 所有者可执行(x)。 |
| 0070 | 所属组可读、可写、可执行(rwx)。 |
| 0040 | 所属组可读(r)。 |
| 0020 | 所属组可写(w)。 |
| 0010 | 所属组可执行(x)。 |
| 0007 | 其他用户可读、可写、可执行(rwx)。 |
| 0004 | 其他用户可读(r)。 |
| 0002 | 其他用户可写(w)。 |
| 0001 | 其他用户可执行(x)。 |
| 4000 | Set-UID 位(执行时以文件所有者身份运行)。 |
| 2000 | Set-GID 位(执行时以文件所属组身份运行)。 |
| 1000 | Sticky 位(粘滞位,常用于公共临时目录防误删)。 |
离线校验 Ruby 控制台 I/O、文件读写模式、元数据查询、目录与临时文件操作
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 27 (input-output)."""
import io
import json
import os
import stat
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_console_io_puts_print_putc_gets():
# Simulate Ruby Kernel#puts, print, putc, gets on in-memory IO streams
buf_puts = io.StringIO()
for v in ("This is variable one", "This is variable two"):
buf_puts.write(v + "\n")
buf_print = io.StringIO()
buf_print.write("Hello World")
buf_print.write("Good Morning")
buf_putc = io.StringIO()
s = "Hello Ruby!"
buf_putc.write(s[0])
fake_stdin = io.StringIO("This is entered value\n")
val = fake_stdin.readline()
expected = {
"puts_out": "This is variable one\nThis is variable two\n",
"print_out": "Hello WorldGood Morning",
"putc_out": "H",
"gets_val": "This is entered value\n",
}
actual = {
"puts_out": buf_puts.getvalue(),
"print_out": buf_print.getvalue(),
"putc_out": buf_putc.getvalue(),
"gets_val": val,
}
return {
"name": "console_io_puts_print_putc_gets",
"summary": "核验 puts 自动换行、print 连续输出、putc 仅输出首字符与 gets 读取含换行符的一行",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_modes_and_sys_rw_ops():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "input.txt"
text = "This is a simple text file for testing purpose."
p.write_text(text, encoding="utf-8")
# sysread(20) equivalent: read first 20 bytes and advance cursor to byte 20 (21st byte)
with p.open("rb") as fh:
head20 = fh.read(20).decode("utf-8")
pos_after = fh.tell()
# r+ syswrite("ABCDEF"), rewind, each_byte with '.' separator
with p.open("r+b") as fh:
fh.write(b"ABCDEF")
fh.seek(0)
raw = fh.read()
dotted = "".join(chr(b) + "." for b in raw)
# IO.readlines & IO.foreach on multi-line file
ml = Path(tmp) / "lines.txt"
ml.write_text("line1\nline2\n", encoding="utf-8")
lines_arr = ml.read_text(encoding="utf-8").splitlines(keepends=True)
foreach_lines = [ln.strip() for ln in lines_arr]
expected = {
"head20": "This is a simple tex",
"pos_after": 20,
"dotted_prefix": "A.B.C.D.E.F.s. .a. .",
"readlines_count": 2,
"foreach_lines": ["line1", "line2"],
}
actual = {
"head20": head20,
"pos_after": pos_after,
"dotted_prefix": dotted[:20],
"readlines_count": len(lines_arr),
"foreach_lines": foreach_lines,
}
return {
"name": "file_modes_and_sys_rw_ops",
"summary": "在隔离临时目录核验 r/r+/w 模式、定长读取指针前移、r+ 覆写前 6 字节与逐行/逐字节读取",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_queries_chmod_and_rename():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
f1 = root / "test1.txt"
f2 = root / "test2.txt"
f1.write_text("ruby-io", encoding="utf-8")
empty = root / "empty.txt"
empty.write_bytes(b"")
# Rename & query predicates
f1.rename(f2)
st = f2.stat()
mode_octal = oct(0o755)
expected = {
"f1_exists": False,
"f2_is_file": True,
"root_is_dir": True,
"empty_is_zero": True,
"f2_size": 7,
"ftype_regular": "file",
"has_timestamps": True,
"chmod_0755_octal": "0o755",
}
actual = {
"f1_exists": f1.exists(),
"f2_is_file": f2.is_file(),
"root_is_dir": root.is_dir(),
"empty_is_zero": empty.stat().st_size == 0,
"f2_size": st.st_size,
"ftype_regular": "file" if stat.S_ISREG(st.st_mode) else "other",
"has_timestamps": st.st_mtime > 0 and st.st_atime > 0 and st.st_ctime > 0,
"chmod_0755_octal": mode_octal,
}
f2.unlink()
return {
"name": "file_queries_chmod_and_rename",
"summary": "核验 File.rename/delete、exist?/file?/directory?/zero?/size?/ftype/mtime 及八进制权限掩码 0755",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dir_ops_and_tempfile():
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
sub = base / "mynewdir"
sub.mkdir()
(sub / "a.rb").write_text("puts 1\n", encoding="utf-8")
entries = sorted(os.listdir(sub))
globbed = [p.name for p in sub.glob("*")]
(sub / "a.rb").unlink()
sub.rmdir()
# Tempfile lifecycle
with tempfile.NamedTemporaryFile(prefix="tingtong", dir=tmp, delete=False, mode="w", encoding="utf-8") as tf:
tf.write("Hello\n")
tf_path = Path(tf.name)
tf_exists_before = tf_path.exists()
tf_content = tf_path.read_text(encoding="utf-8")
tf_path.unlink()
tf_exists_after = tf_path.exists()
expected = {
"entries": ["a.rb"],
"globbed": ["a.rb"],
"sub_removed": True,
"tempfile_content": "Hello\n",
"tempfile_cleanup": [True, False],
}
actual = {
"entries": entries,
"globbed": globbed,
"sub_removed": not sub.exists(),
"tempfile_content": tf_content,
"tempfile_cleanup": [tf_exists_before, tf_exists_after],
}
return {
"name": "dir_ops_and_tempfile",
"summary": "核验 Dir.mkdir/entries/glob/delete 与 tmpdir/Tempfile 临时文件创建及清理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_console_io_puts_print_putc_gets(),
case_file_modes_and_sys_rw_ops(),
case_file_queries_chmod_and_rename(),
case_dir_ops_and_tempfile(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`File.open` 搭配代码块在块退出(包括发生异常)时会自动关闭文件句柄,避免文件描述符泄漏。