No method read_to_string found, simple file handling

So i've been playing with file handling and well i keep getting an error thrown at me but i can firugre it out for the life of me... Basically ive got a method which returns a boolean value. True if ran correctly, else false. However i keep getting an error and dispite my googling of the issue i have been unable to resolve it.

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

fn open_new(full_path: &str){
  let mut file_contents = File::open( full_path );
  let mut file_contents_as_string = String::new();

  file_contents.read_to_string(&mut file_contents_as_string);


}

fn main(){
    open_new("text.txt")
}

The Error is as follows:
error[E0599]: no method named read_to_string found for typestd::result::Result<std::fs::File, std::io::Error> in the current scope --> test.rs:9:17 | 9 | file_contents.read_to_string(&mut file_contents_as_string); | ^^^^^^^^^^^^^^

2 Likes

File::open() is a fallible operation (ie can fail). As such, it returns a Result<File, io::Error>. If you don’t care about error handling here, you can unwrap or expect file_contents to get the File out and then call read_to_string on that.

Is there anyway i can get a more accurate error to figure out exactly why its failing? The path is correct, the file exists. I just cannot understand why it cannot read the file into a string.

That was a compilation error, not a runtime error. You’re simply calling a method on a type that doesn’t have that method. You need to get the File from the Result first. Eg:

// unwrap will panic if open returns Err
// if it returns Ok, file is now of type File  
let file = File::open(...).unwrap();

omg thats it... sorry. Tried unwrap and expect on the actual read_to_string line just not on the file open.