注意:这个答案是关于 Rust 1.0 之前的,因此已经过时了。有关最新答案,请参阅链接的副本。
是的,0.8 太旧了,对于 0.10-pre 的 master 分支,我会使用:
use std::io::BufferedReader;
use std::io::File;
use std::from_str::from_str;
let fname = "in.txt";
let path = Path::new(fname);
let mut file = BufferedReader::new(File::open(&path));
for line_iter in file.lines() {
let line : ~str = match line_iter { Ok(x) => x, Err(e) => fail!(e) };
// preprocess line for further processing, say split int chunks separated by spaces
let chunks: ~[&str] = line.split_terminator(|c: char| c.is_whitespace()).collect();
// then parse chunks
let terms: ~[int] = vec::from_fn(nterms, |i: uint| parse_str::<int>(chunks[i+1]));
...
}
在哪里
fn parse_str<T: std::from_str::FromStr>(s: &str) -> T {
let val = match from_str::<T>(s) {
Some(x) => x,
None => fail!("string to number parse error")
};
val
}
写入文本文件:
use std::io::{File, Open, Read, Write, ReadWrite};
use std::path::Path;
let fname = "out.txt"
let p = Path::new(fname);
let mut f = match File::open_mode(&p, Open, Write) {
Ok(f) => f,
Err(e) => fail!("file error: {}", e),
};
那么你可以使用任何
f.write_line("to be written to text file");
f.write_uint(5);
f.write_int(-1);
文件描述符将在范围退出时自动关闭,因此没有 f.close() 方法。希望这会有所帮助。