#文件与网络 IO
本章介绍程序如何与外部世界交互。文件和目录、路径、标准 IO、环境变量、子进程以及 TCP / UDP 套接字都在 std 中。
IO 随时可能失败,所以几乎每个函数都是 throws (IoError)。第 10 章的 try / catch 贯穿全章。示例写 fn main() throws (IoError) 来说明可能失败的地方;普通的 fn main() 同样可以使用 try,从中传出的错误会被打印出来,并以退出码 1 结束程序。
#读写文件
最简单的方式是 fs::write 和 fs::read_to_str。这两个函数会替你打开和关闭文件。示例在 env::temp_dir() 下创建一个目录,在其中工作,最后删除它。
use std::fs;
use std::env;
use std::process;
use core::io::IoError;
fn main() throws (IoError) {
let dir = env::temp_dir() / f"nabi_learn13_{process::id()}";
try fs::create_dir_all(dir / "notes" / "2026");
try fs::write(dir / "hello.txt", "first line\nsecond line\n");
let text = try fs::read_to_str(dir / "hello.txt");
print(text);
println(f"{text.lines().count()} lines");
try fs::read_to_str(dir / "nope.txt") catch e {
println(f"error kind: {e.kind():?}");
""
};
try fs::remove_dir_all(dir);
println(f"exists after cleanup: {fs::exists(dir)}");
}
first line
second line
2 lines
error kind: NotFound
exists after cleanup: false
IoError 带有一个 kind()(NotFound、PermissionDenied、TimedOut,另一个进程占用文件或设备时为 ResourceBusy,……)和一条供人阅读的消息。要按错误种类分支,比较 kind() 即可。
路径参数接受 str 或 Path(AsPath trait),所以 "a.txt" 和 dir / "a.txt" 都可以传。
fs::lines(path) 逐行读取文件,在读第一行时打开文件,在最后一行之后关闭:try for line in fs::lines(p) { .. }。fs::glob(pattern) 列出匹配的路径并排序:* 和 ? 匹配名称内的字符,[a-z] 匹配一个字符集,** 组件匹配任意层目录。
use std::{env, fs, process};
fn main() {
let dir = env::temp_dir() / f"nabi_learn13_glob_{process::id()}";
try fs::create_dir_all(dir / "src");
try fs::write(dir / "a.txt", "one\ntwo\n");
try fs::write(dir / "src" / "b.txt", "three\n");
try for line in fs::lines(dir / "a.txt") { println(line); }
for p in try fs::glob(f"{dir}/**/*.txt") {
println(p.strip_prefix(dir) ?? p);
}
try fs::remove_dir_all(dir);
}
one
two
a.txt
src/b.txt
#File 及其打开函数
要增量写入或逐行读取,直接打开一个 File。使用 using 块时,文件在块退出时关闭;语句 using f = ..; 则在外层块结束时关闭它,如下面的 show。关闭文件可能失败,所以编译器不会替你关闭:用 using 绑定,或调用 try f.close();留下未关闭的 File 是编译错误。每种打开方式都是独立的函数,所以写不出错误的组合:File::open(已有文件,只读,除非传入 WriteOnly 等 Access)、File::create(创建或清空)、File::create_new(文件已存在时失败)、File::open_or_create,以及 File::append(不存在时创建,每次写入都追加到末尾)。
use std::fs;
use std::fs::File;
use std::env;
use std::process;
use std::path::Path;
use core::io::{IoError, BufReader};
fn show(log: Path) throws (IoError) {
using r = BufReader::new(try File::open(log));
try for line in r.lines() {
println(f"> {line}");
}
}
fn main() throws (IoError) {
let log = env::temp_dir() / f"nabi_learn13_log_{process::id()}.txt";
using f = try File::create(log) {
try f.write_all("start\n");
}
using f = try File::append(log) {
try f.write_all("more\n");
}
try show(log);
try fs::remove_file(log);
}
> start
> more
File::create 创建或截断文件,File::open 以只读方式打开。读和写是 io::Read 和 io::Write trait 的方法,每个文件不用 use 就具备这些方法。逐行读取需要缓冲区,所以把文件包进 io::BufReader;关闭读取器就会关闭文件。想沿用原来的名字,就重新声明:let f = BufReader::new(f); 把文件移动进读取器,于是只需关闭读取器。lines() 给出不含换行符的每一行,读取错误会通过抛出来结束循环,所以写成 try for。
r.lines() 是 r 的视图:它通过读取器读取,并且只能留在 r 的所有者的作用域内。从函数返回它、让它活过那个作用域,或在任务中捕获它,都是编译错误(E0139),错误会指出修改方法:
error[E0139]: this returns a view of `r` out of `r`'s scope --> main.nabi:6:9 | 6 | return r.lines(); | ^^^^^^ | --------- a view of `r` made here | = help: `r.lines()` reads through `r` and stays in its scope; use it there (`try r.lines().collect()`), or take the owning form `r.into_lines()`, which owns `r` and closes it with itself
移动 r 同样会结束它的视图:在 let kept = r;、按值接收 r 的调用、[move r] 或把 r 存入结构体之后,之前由它生成的视图就不能再用了。先用完视图,或者改为移动拥有所有权的形式。
只为一次借用它的调用而创建的读取器或文件,例如 (try File::open(p)).read_to_str() 或 BufReader::new(try File::open(p)).lines(),在调用之后就没有所有者,也就没有谁会关闭它。这就是 E0134;先绑定它:using f = try File::open(p);,再 try f.read_to_str()。
需要让这些行离开作用域时,使用拥有所有权的形式 r.into_lines()。它返回一个 io::Owned,后者接管读取器,在你关闭这些行时关闭它(try ls.close()),可以用 into_inner() 交还它,也可以被返回或移动进任务(读取器是 Send 时它也是 Send):
use std::fs;
use std::fs::File;
use std::env;
use std::process;
use core::io::{IoError, BufReader, Lines, Owned};
// The lines own the reader, so they can leave the function.
fn open_lines(path: str) throws (IoError) -> Owned<Lines<BufReader<File>>, BufReader<File>> {
BufReader::new(try File::open(path)).into_lines()
}
fn main() throws (IoError) {
let log = env::temp_dir() / f"nabi_learn13_owned_{process::id()}.txt";
try fs::write(log, "start\nmore\n");
let ls = try open_lines(log.as_str());
try for line in ls {
println(f"> {line}");
}
try ls.close(); // closes the reader and the file
try fs::remove_file(log);
}
> start
> more
同样成对的还有 bytes / into_bytes、split / into_split、take / into_take,异步的 lines_async / into_lines_async 和 bytes_async / into_bytes_async,以及监听器的 incoming / into_incoming。a.chain(b) 总是拥有两个读取器并关闭两者,into_inner() 交还这一对。take 视图没有 into_inner();之后若要取回读取器,使用 into_take 及其 into_inner()。
#目录与 Dir 能力
fs::walk 按名称顺序深度优先遍历目录。fs::read_dir 只列出一层。读取目录可能在任何一项上失败,所以两者都用 try for 逐步遍历。
Dir 有点特殊:Dir 句柄是一种能力(capability)。Dir::root() 是处理普通路径的默认句柄,由它用 open_dir 打开的 Dir 只能访问该目录内部。试图用绝对路径或 .. 逃出去会被拒绝。处理不可信的路径(用户输入、压缩包内的名称)时,这是一张安全网。
use std::fs;
use std::fs::Dir;
use std::env;
use std::process;
use core::io::IoError;
fn main() throws (IoError) {
let base = env::temp_dir() / f"nabi_learn13_dir_{process::id()}";
try fs::create_dir_all(base / "notes" / "2026");
try fs::write(base / "notes" / "a.md", "# a");
try fs::write(base / "notes" / "2026" / "b.md", "# b");
try for e in fs::walk(base) {
let rel = e.path().strip_prefix(base) ?? e.path();
if rel.as_str() != "" { println(f"{rel} dir={e.is_dir()}"); }
}
using d = try Dir::root().open_dir(base / "notes") {
println(f"inside: {d.exists("a.md")}");
try d.open("../../escape.txt").close() catch e { println(f"refused: {e.kind():?}"); };
try d.open("/etc/hosts").close() catch e { println(f"refused: {e.kind():?}"); };
}
try fs::remove_dir_all(base);
}
notes dir=true
notes/2026 dir=true
notes/2026/b.md dir=false
notes/a.md dir=false
inside: true
refused: PermissionDenied
refused: PermissionDenied
create_dir、remove_file、remove_dir、rename、copy 和 metadata 也都既有自由函数形式,也有 Dir 方法形式。
#路径:Path
std::path::Path 是 UTF-8 路径。和 Python 的 pathlib 一样,用 / 运算符拼接路径。路径可能没有父目录或扩展名,所以这些方法返回 T | none。
use std::path::Path;
let p = Path::new("/home/nabi/src/main.nabi");
println(f"parent: {p.parent() ?? Path::empty()}");
println(f"file name: {p.file_name() ?? "-"}");
println(f"stem: {p.file_stem() ?? "-"}");
println(f"extension: {p.extension() ?? "-"}");
println(f"absolute: {p.is_absolute()}");
let q = Path::new("docs") / "guide" / "intro.md";
println(f"joined: {q}");
println(f"swapped: {q.with_extension("html")}");
println(f"normal: {Path::new("a/./b/../c").normalize()}");
for c in q.components() { print(f"[{c.as_str()}]"); }
println("");
parent: /home/nabi/src
file name: main.nabi
stem: main
extension: nabi
absolute: true
joined: docs/guide/intro.md
swapped: docs/guide/intro.html
normal: a/c
[docs][guide][intro.md]
normalize 只整理字符串;canonicalize 会询问文件系统,并且还会解析符号链接。
#标准 IO 与环境
print 写出时不带换行,eprint / eprintln 写到标准错误;需要缓冲或显式写入时,使用 io::stdout() / io::stderr()。io::input("Your name? ") 写出提示并刷新,然后返回下一行(不含换行符),到输入末尾时返回 none,与 Python 的 input 相同;io::read_line() 做同样的事但不带提示;要读取所有行,写 try for line in io::stdin().lines()。io 模块以及 Read / Write trait 不需要 use。
use core::io::IoError;
fn main() throws (IoError) {
let out = io::stdout();
try out.write_all("Your name? ");
try out.flush();
match try io::read_line() {
line: str => println(f"Hello, {line.trim()}!"),
none => println("(no input)"),
}
try io::stderr().write_all("bye\n");
}
命令行参数和环境变量在 std::env 中。env::args() 的第 0 个元素是可执行文件的路径。变量未设置时,env::var 抛出 VarError。
use std::env;
let args = env::args();
println(f"{args.len()} arg(s)");
unsafe { try! env::set_var("NABI_GREETING", "annyeong"); }
println(try env::var("NABI_GREETING") catch _ { "unset" });
unsafe { try! env::remove_var("NABI_GREETING"); }
println(try env::var("NABI_GREETING") catch e { f"error: {e}" });
let mine = env::vars().filter(|kv| kv.0.starts_with("NABI_GREETING")).count();
println(f"matching vars: {mine}");
println(f"temp is absolute: {env::temp_dir().is_absolute()}");
1 arg(s)
annyeong
error: environment variable not found
matching vars: 0
temp is absolute: true
set_var 和 remove_var 是 unsafe 的,并且会抛出错误。Nabi 自己的 env 函数共用一把锁,但无法阻止 C 代码同时读取环境,所以请在创建线程之前修改它。名称为空,或含有 = 或 NUL 时,抛出 IoError(InvalidInput)。只想为某一个子进程设置变量,使用 Command::env,它不需要 unsafe。
#子进程
process::Command 运行另一个程序。用构建器方法设置参数、环境和工作目录,然后用以下之一运行:output()(等待退出并收集 stdout / stderr)、status()(只要退出状态)或 spawn()(不等待,返回一个 Child)。
use std::process::Command;
use core::io::IoError;
fn main() throws (IoError) {
let out = try Command::new("echo").args(["hello", "from", "echo"]).output();
print(try str::from_utf8(out.stdout) catch _ { "" });
println(f"success: {out.status.success()}");
let st = try Command::new("sh").args(["-c", "exit 3"]).status();
println(f"code: {st.code() ?? -1}");
try Command::new("no-such-program").status() catch e {
println(f"spawn failed: {e.kind():?}");
};
}
hello from echo
success: true
code: 3
spawn failed: NotFound
out.stdout 是字节(List<u8>),所以用 str::from_utf8 转换成文本。只想以文本形式得到输出时,process::run("git", ["status"]) 运行程序直到结束并返回其 stdout;非零退出会抛出 ExitStatusError,它的 status() 和 stderr() 说明发生了什么。对于被信号杀死的进程,code() 是 none;在 Linux 和 macOS 上,st.signal() 给出是哪个信号(Signal::Kill,..)。构建器方法返回修改后的副本,被调用的命令保持原样,所以 let base = Command::new("git"); let log = base.arg("log"); 中的 base 不带 log。
子进程的流去往 Stdio 指定的地方。使用 Stdio::Piped 时,用 take_stdin()、take_stdout() 或 take_stderr() 从 Child 取出各个管道(该流没有接管道或已被取走时为 none);取走者拥有并负责关闭它。移入 Stdio::File(f) 的 File 属于该命令:运行命令会关闭你手里的那份,所以移动之后 f 就没有了,而子进程保留它自己的一份。带有 Stdio::File 的命令只能运行一次;要再次运行,给它一个新文件(f.try_clone())。Stdio::File 值同样只有一个所有者:把它交给两个命令,或交给同一命令的两个流(.stdout(s).stderr(s)),是错误(E0133);给每个各自的 Stdio::File(try f.try_clone())。Stdio::Inherit、Null 和 Piped 不持有任何东西,可以重复使用。从未交给命令的 Stdio::File 必须关闭(try s.close()),与其 File 一样。
Child 只有一个所有者,即等待它的那一方。要在所有者等待期间从别处停止子进程(超时、关机),取出 child.handle():这是一个 ChildHandle,其他线程或任务可以用它 kill() 子进程或对其 send_signal(..)。它不拥有任何管道,也不负责等待;h.id() 给出子进程的进程 ID,子进程结束之后,通过它发出的信号不起任何作用。
#TCP 与 UDP
std::net API 默认是阻塞的。下面的示例在一个程序中运行服务器和客户端。绑定到端口 0 让操作系统挑选一个空闲端口,local_addr() 报告实际地址。服务器在一个线程上接受一个连接,并把收到的文本转为大写发回。
地址可以是 SocketAddr、"host:port" 文本(会查找名称)、(IpAddr, u16) 对或地址列表:TcpStream::connect、TcpListener::bind 和 UdpSocket::bind 接受任何实现了 ToSocketAddrs 的值,并依次尝试各个地址。net::tcp_connect、net::tcp_listen 和 net::udp_bind 是对应的自由函数。
关闭套接字可能失败,所以每个套接字都由其所有者关闭,用 try s.close() 或 using;留下未关闭套接字的程序会被编译器拒绝。
use std::net::{TcpListener, TcpStream, Shutdown};
use core::io::IoError;
use std::thread;
fn main() throws (IoError) {
let listener = try TcpListener::bind("127.0.0.1:0");
let addr = try listener.local_addr();
let server = thread::spawn(|| {
let (conn, _) = try! listener.accept();
let msg = try! conn.read_to_str();
try! conn.write_all(msg.to_uppercase());
try! conn.close();
try! listener.close(); // the thread owns the listener now
msg.len()
});
let client = try TcpStream::connect(addr);
try client.write_all("hello, socket");
// Half-close: the server's read_to_str sees the end.
try client.shutdown(Shutdown::Write);
println(f"reply: {try client.read_to_str()}");
try client.close();
println(f"server read {try! server.join()} bytes");
}
reply: HELLO, SOCKET
server read 13 bytes
要同时从两个线程或任务读写同一个连接,用 split() 把它拆成 ReadHalf 和 WriteHalf。每一半拥有自己的方向,由各自的所有者关闭。关闭写的一半会为对端结束流,效果同 shutdown(Shutdown::Write),而读的一半继续读取回复;第二个一半关闭时套接字随之关闭。对任一半调用 shutdown(Shutdown::Both) 会双向关闭套接字,并唤醒阻塞在另一半上的读取。r.unsplit(w) 交还连接。UnixStream 和 TLS 连接也以同样方式拆分。
use std::net::{TcpListener, TcpStream, WriteHalf};
use core::io::IoError;
use std::thread;
fn send(w: WriteHalf<TcpStream>) -> i32 {
try! w.write_all("hello, halves");
try! w.close(); // the server's read_to_str sees the end
0
}
fn main() throws (IoError) {
let listener = try TcpListener::bind("127.0.0.1:0");
let addr = try listener.local_addr();
let server = thread::spawn(|| {
let (conn, _) = try! listener.accept();
try! listener.close();
let msg = try! conn.read_to_str();
try! conn.write_all(msg.to_uppercase());
try! conn.close();
0
});
let (r, w) = (try TcpStream::connect(addr)).split();
let writer = thread::spawn(|| send(w));
println(f"reply: {try r.read_to_str()}");
try r.close(); // the socket closes with the second half
_ = try! writer.join();
_ = try! server.join();
}
reply: HELLO, HALVES
UDP 在不建立连接的情况下交换数据报。recv_from 返回收到的字节数和发送方的地址。
use std::net;
use core::io::IoError;
fn main() throws (IoError) {
let a = try net::udp_bind("127.0.0.1:0");
let b = try net::udp_bind("127.0.0.1:0");
try b.send_to("ping", try a.local_addr());
let buf = List::filled(64, 0u8);
let (n, from) = try a.recv_from(buf);
println(f"got {n} bytes: {try str::from_utf8(buf[0:n]) catch _ { "?" }}");
println(f"from b: {from == (try b.local_addr())}");
try a.close();
try b.close();
}
got 4 bytes: ping
from b: true
在这些之下是 net::Socket,即操作系统所持有的套接字:由你选择域、类型和协议,设置 set_reuse_address 或 set_only_v6 等选项,并自己调用 bind / listen / connect。然后由 TcpListener::from(s)(或 TcpStream::from、UdpSocket::from)接管。
use std::net::{Socket, Domain, SocketType, Protocol, TcpListener};
use core::io::IoError;
fn main() throws (IoError) {
let s = try Socket::new(Domain::Ipv4, SocketType::Stream, Protocol::TCP);
try s.set_reuse_address(true);
try s.bind(try! "127.0.0.1:0".parse());
try s.listen(16);
let l = TcpListener::from(s);
println(f"listening on port 0: {(try l.local_addr()).port() > 0}");
try l.close();
}
listening on port 0: true
#异步 IO:*_async
在任务内部(见第 12 章),不使用阻塞调用,而是 await 带 _async 后缀的同名版本。对于套接字,等待时只有任务暂停,线程会去运行其他任务。普通文件没有操作系统层面的异步等待支持,所以调用在单独的线程上运行,任务则等待结果。错误的抛出方式与同步版本完全相同。
use std::fs;
use std::fs::File;
use std::net;
use std::net::{TcpStream, Shutdown};
use std::env;
use std::process;
let path = env::temp_dir() / f"nabi_learn13_async_{process::id()}.txt";
try! await fs::write_async(path, "written in a task");
let f = try! await File::append_async(path);
try! await f.write_all_async(", then appended");
try! await f.close_async();
println(try! await fs::read_to_str_async(path));
try! await fs::remove_file_async(path);
let l = try! net::tcp_listen("127.0.0.1:0");
let addr = try! l.local_addr();
let server = task::spawn(async {
let (conn, _) = try! await l.accept_async();
try! await l.close_async();
let got = try! await conn.read_to_end_async();
try! await conn.close_async();
got.len()
});
let c = try! await TcpStream::connect_async(addr);
try! await c.write_all_async("twelve bytes");
try! await c.shutdown_async(Shutdown::Write);
try! await c.close_async();
println(f"server got {await server} bytes");
written in a task, then appended
server got 12 bytes
流操作来自 io trait。AsyncRead、AsyncWrite、AsyncSeek 和 AsyncClose 为每个文件、套接字、TLS 连接和子进程管道,以及以它们为约束的你自己的代码,提供 read_async、write_all_async、flush_async、seek_async 和 close_async。close_async 像 close 一样关闭值,所以也算作关闭。只有不属于读写流的操作才是其类型的方法:connect_async、accept_async、shutdown_async,以及子进程的 Child::wait_async、Command::output_async 和 Command::status_async。异步方法会更新调用它的值,所以在调用处就 await 它(第 12 章)。
连接数达到数千时,任务比每个连接一个线程轻量得多。对于只有少量连接的工具,阻塞 API 更简单。
#小结
- 整个文件:
fs::read_to_str/fs::write。增量读写:File+using,按需要的方式选用打开函数(open、create、create_new、open_or_create、append)。 Dir是一种能力。已打开的Dir之外的任何东西(绝对路径、..)都会以PermissionDenied被拒绝。- 用
Path和/运算符构造路径;可能缺失的部分以T | none返回。 - 用
io::stdin/stdout/stderr、env::args/var/temp_dir、io::input以及process::run/process::Command与外部环境打交道。fs::lines和fs::glob读取行、匹配路径。 - TCP / UDP:基于
ToSocketAddrs的TcpListener::bind/TcpStream::connect/UdpSocket::bind(或net::tcp_listen/net::tcp_connect/net::udp_bind);所有选项都可通过net::Socket设置。使用端口0时由操作系统挑选。关闭每个套接字:try s.close()或using。用split()拆分连接,以便从两个线程或任务读写。 - 在任务内部,
await各个*_async版本;用try await s.close_async()关闭。 r.lines()和其他适配器是留在r作用域内的视图;r.into_lines()和其他into_形式拥有读取器,可以离开作用域。
#延伸阅读
发现错误? 在 GitHub 上编辑此页 最后更新: