Created
April 25, 2021 06:20
-
-
Save davidlopezre/095fb1d5e5d74fd41f75889754bb32c8 to your computer and use it in GitHub Desktop.
Rust program to read a file specified by user input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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