【问题标题】:How can I read and write a text file in Rust? [duplicate]如何在 Rust 中读写文本文件? [复制]
【发布时间】:2013-11-08 08:24:51
【问题描述】:

注意:这个问题是关于 Rust 1.0 之前的问题,因此已经过时。有关最新答案,请参阅 the linked duplicate

我正在 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");   
}

如果文件存在,上述“有效”。

有人可以给我看一个例子,说明如何按照我所说的要求去做吗?

【问题讨论】:

标签: rust rust-0.8


【解决方案1】:

注意:这个答案是关于 Rust 1.0 之前的,因此已经过时了。请参阅 the linked duplicate 获取最新答案。

是的,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() 方法。 希望这会有所帮助。

【讨论】:

  • 你从哪里拉出nterms?这是什么?
  • 你能为 Rust 1.0 更新它吗?
猜你喜欢
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 2019-06-04
  • 2019-12-16
  • 2020-02-03
  • 1970-01-01
相关资源
最近更新 更多