如何在Rust中读写文本文件?

Bri*_* Oh 15 rust rust-0.8

我正在Win8上使用Rust 0.8编写测试程序,我需要使用数组/矢量/列表读取和写入程序使用的一些参数来访问/从文本文件中访问各行.

在花了相当多的时间试图找到有用的东西之后,我能找到的最接近的东西如下:

use std::rt::io::{file, Open};
use std::path::Path;
use std::rt::io::file::FileInfo;

fn main () {

    let mut reader : file::FileReader = Path("xxxx.txt").open_reader(Open)  
    .expect("'xxxx.txt' could not be opened");

    println("Completed");   
}
Run Code Online (Sandbox Code Playgroud)

如果文件存在,上述"有效".

有人可以告诉我一个如何做我所说的要求的例子吗?

Ale*_*lov 6

是的,0.8太旧了,对于0.10-pre的主分支我会使用:

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]));
    ...
}
Run Code Online (Sandbox Code Playgroud)

哪里

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
}
Run Code Online (Sandbox Code Playgroud)

写入文本文件:

use std::io::{File, Open, Read, Write, ReadWrite};

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),
};
Run Code Online (Sandbox Code Playgroud)

然后你可以使用任何一个

f.write_line("to be written to text file");
f.write_uint(5);
f.write_int(-1);
Run Code Online (Sandbox Code Playgroud)

文件描述符将在作用域的出口处自动关闭,因此没有f.close()方法.希望这会有所帮助.

  • 你能为Rust 1.0更新它吗? (3认同)