18

Note: this question is about pre Rust 1.0 and thus outdated. See the linked duplicate for an up to date answer.

I'm writing a test program using Rust 0.8 on Win8, and I need to read and write some parameters used by the program to/from a text file using an array/vector/list to access individual lines.

After spending considerable time attempting to find something that works, the closest that I could find is as follows :

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

The above "works" if the file exists.

Could someone please show me an example of how to do what I have stated as the requirement?

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Brian Oh
  • 9,604
  • 12
  • 49
  • 68
  • 2
    0.8 is so old in `rust` world, now you need `let filereader = File::open(p)` – cnd Nov 23 '13 at 10:57
  • As of 1.7, see the examples for BufReader in the reference docs: http://doc.rust-lang.org/std/io/struct.BufReader.html#examples – steamer25 Mar 17 '16 at 21:41

1 Answers1

9

Note: this answer is about pre Rust 1.0 and thus outdated. See the linked duplicate for an up to date answer.

Yes, 0.8 is too old, for master branch of 0.10-pre I'd use:

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]));
    ...
}

where

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
}

Writing to text file:

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),
};

then you can use any of

f.write_line("to be written to text file");
f.write_uint(5);
f.write_int(-1);

The file descriptor will be closed automatically on the exit of the scope, so there is no f.close() method. Hope this would help.

Qaz
  • 45
  • 1
  • 4