File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // vim: set ft=rust ts=8 sw=4 sts=4 et :
2+ // START_INDENT
3+ use std:: fs:: File ;
4+ use std:: io:: prelude:: * ;
5+ use std:: path:: Path ;
6+
7+ fn main ( ) {
8+ // Create a path to the desired file
9+ let path = Path :: new ( "hello.txt" ) ;
10+ let display = path. display ( ) ;
11+
12+ // Open the path in read-only mode, returns `io::Result<File>`
13+ let mut file = match File :: open ( & path) {
14+ Err ( why) => panic ! ( "couldn't open {}: {}" , display, why) ,
15+ Ok ( file) => file,
16+ } ;
17+
18+ // Read the file contents into a string, returns `io::Result<usize>`
19+ let mut s = String :: new ( ) ;
20+ match file. read_to_string ( & mut s) {
21+ Err ( why) => panic ! ( "couldn't read {}: {}" , display, why) ,
22+ Ok ( _) => print ! ( "{} contains:\n {}" , display, s) ,
23+ }
24+
25+ // file goes out of scope, and the "hello.txt" file gets closed
26+ }
27+ // END_INDENT
Original file line number Diff line number Diff line change 1+ // vim: set ft=rust ts=8 sw=4 sts=4 et :
2+ // START_INDENT
3+ use std:: fs:: File ;
4+ use std:: io:: prelude:: * ;
5+ use std:: path:: Path ;
6+
7+ fn main ( ) {
8+ // Create a path to the desired file
9+ let path = Path :: new ( "hello.txt" ) ;
10+ let display = path. display ( ) ;
11+
12+ // Open the path in read-only mode, returns `io::Result<File>`
13+ let mut file = match File :: open ( & path) {
14+ Err ( why) => panic ! ( "couldn't open {}: {}" , display, why) ,
15+ Ok ( file) => file,
16+ } ;
17+
18+ // Read the file contents into a string, returns `io::Result<usize>`
19+ let mut s = String :: new ( ) ;
20+ match file. read_to_string ( & mut s) {
21+ Err ( why) => panic ! ( "couldn't read {}: {}" , display, why) ,
22+ Ok ( _) => print ! ( "{} contains:\n {}" , display, s) ,
23+ }
24+
25+ // file goes out of scope, and the "hello.txt" file gets closed
26+ }
27+ // END_INDENT
You can’t perform that action at this time.
0 commit comments