Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust reading a file [duplicate]

I'm trying to read a file named enable.txt that's in the same dir as my main.rs, and my code looks like this:

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::error::Error;
fn main() {
    let path = Path::new("enable.txt");
    let display = path.display();
    let mut file = File::open(&path);
    let mut contents = String::new();
    file.read_to_string(&mut contents);
    println!("{}", contents);
}

When I compile it with either cargo run or rustc src/main.rs, I get this error message:

error: no method named `read_to_string` found for type `std::result::Result<std::fs::File, std::io::Error>` in the current scope
  --> src/main.rs:10:10
   |
10 |     file.read_to_string(&mut contents);
   |          ^^^^^^^^^^^^^^
like image 710
Vinayak G. Avatar asked Sep 12 '25 14:09

Vinayak G.


1 Answers

The issue is that File::open() returns a std::result::Result<std::fs::File, std::io::Error> which needs to be unwrapped in some way in order to access the file. The way I prefer to do this is to use expect() like this:

...
fn main() {
    ...
    let mut file = File::open(&path).expect("Error opening File");
    ...
    file.read_to_string(&mut contents).expect("Unable to read to string");
    ...
}

This will either return the expected value or panic with the error message provided depending on if the operation was successful.

like image 143
Alex Zywicki Avatar answered Sep 14 '25 06:09

Alex Zywicki