Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read and write a text file in Rust? [duplicate]

Tags:

rust

rust-0.8

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?

like image 346
Brian Oh Avatar asked Nov 08 '13 08:11

Brian Oh


People also ask

What is write in Rust?

write { ($dst:expr, $($arg:tt)*) => { ... }; } Writes formatted data into a buffer. This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be formatted according to the specified format string and the result will be passed to the writer.

How do you close a file in Rust?

Closing the file is done by dropping the std::fs::File , which you probably do not want or can do in the data structure you have. To avoid conflicts as you describe, you could wrap the File in a std::cell::RefCell and use try_borrow_mut() whenever you want to write to File , and try_borrow() whenever reading from it.


1 Answers

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.

like image 189
Alexander Samoilov Avatar answered Sep 28 '22 01:09

Alexander Samoilov