Text file reading


#1

Hi. I want to read *.txt file. I took the code from the official documentation, but I have strange error…
Code:

use std::io;
use std::io::prelude::*;
use std::fs::File;

fn main() {
	let mut file = try!(File::open("text.txt"));
	let mut buff = [0; 10];
	try!(file.read(&mut buff));
	println!("{:?}", buff);
}

Errors:

<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
main.rs:6:17: 6:45 note: in this expansion of try! (defined in <std macros>)
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
main.rs:8:2: 8:29 note: in this expansion of try! (defined in <std macros>)
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to 2 previous errors
Could not compile `TestProject`.

#2

So, we have an error about mismatched types. It says that the line is coming

main.rs:8:2: 8:29 note: in this expansion of try! (defined in <std macros>)

Looking at the docs for try!: http://doc.rust-lang.org/std/macro.try!.html

Can only be used in functions that return Result because of the early return of Err that it provides.

But main() does not return a Result, it returns (). Hence the error.

You have a few options. The simplest possible one is to use unwrap(), which causes the program to crash if there is an error:

let mut file = File::open("text.txt").unwrap();

and

file.read(&mut buff).unwrap();

You can introduce a custom message with expect():

let mut file = File::open("text.txt").expect("couldn't find a file!");

This of course is kind of fragile. But for getting started, it works okay.

What to do in a real program depends on how you want to handle errors. Check out this chapter of the book:


#3

I assume Steve meant to link this chapter.


#4

Ah yes, thank you. I should have included it.