Created
May 8, 2016 07:52
-
-
Save complxalgorithm/546c24fe7b6ac3906b122c12a1d32442 to your computer and use it in GitHub Desktop.
Rust program that outputs contents of a particular file (filename and file content are taken as input).
Example:
$ echo "Hello World!" > hello.txt
$ rustc open.rs && ./open
hello.txt contains:
Hello World!
This file contains hidden or 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
// open.rs | |
use std::error::Error; | |
use std::fs::File; | |
use std::io::prelude::*; | |
use std::path::Path; | |
fn main() { | |
// Create a path to the desired file | |
let path = Path::new("hello.txt"); | |
let display = path.display(); | |
// Open the path in read-only mode, returns `io::Result<File>` | |
let mut file = match File::open(&path) { | |
// The `description` method of `io::Error` returns a string that | |
// describes the error | |
Err(why) => panic!("couldn't open {}: {}", display, | |
Error::description(&why)), | |
Ok(file) => file, | |
}; | |
// Read the file contents into a string, returns `io::Result<usize>` | |
let mut s = String::new(); | |
match file.read_to_string(&mut s) { | |
Err(why) => panic!("couldn't read {}: {}", display, | |
Error::description(&why)), | |
Ok(_) => print!("{} contains:\n{}", display, s), | |
} | |
// `file` goes out of scope, and the "hello.txt" file gets closed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment