Skip to content

Instantly share code, notes, and snippets.

@davidlopezre
Created April 25, 2021 06:20
Show Gist options
  • Save davidlopezre/095fb1d5e5d74fd41f75889754bb32c8 to your computer and use it in GitHub Desktop.
Save davidlopezre/095fb1d5e5d74fd41f75889754bb32c8 to your computer and use it in GitHub Desktop.
Rust program to read a file specified by user input
use std::fs::File;
use std::io;
use std::io::Read;
fn main() {
let mut user_input = String::new();
io::stdin().read_line(&mut user_input).expect("Failed to read line");
let result = read_file(String::from(user_input.trim()));
match result {
Ok(s) => println!("contents of file {} is:\n{}", user_input, s),
Err(e) => panic!("{}", e.to_string())
}
}
// this could be much shorter as fs::read_to_string exists and could do this whole function in one line
fn read_file(filename: String) -> Result<String, io::Error> {
let mut file_contents = String::new();
File::open(filename)?.read_to_string(&mut file_contents)?;
Ok(file_contents)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment