@@ -35,21 +35,53 @@ use time::SystemTime;
35
35
///
36
36
/// # Examples
37
37
///
38
+ /// Create a new file and write bytes to it:
39
+ ///
38
40
/// ```no_run
41
+ /// use std::fs::File;
39
42
/// use std::io::prelude::*;
43
+ ///
44
+ /// # fn foo() -> std::io::Result<()> {
45
+ /// let mut file = try!(File::create("foo.txt"));
46
+ /// try!(file.write_all(b"Hello, world!"));
47
+ /// # Ok(())
48
+ /// # }
49
+ /// ```
50
+ ///
51
+ /// Read the contents of a file into a `String`:
52
+ ///
53
+ /// ```no_run
40
54
/// use std::fs::File;
55
+ /// use std::io::prelude::*;
41
56
///
42
57
/// # fn foo() -> std::io::Result<()> {
43
- /// let mut f = try!(File::create("foo.txt"));
44
- /// try!(f.write_all(b"Hello, world!"));
58
+ /// let mut file = try!(File::open("foo.txt"));
59
+ /// let mut contents = String::new();
60
+ /// try!(file.read_to_string(&mut contents));
61
+ /// assert_eq!(contents, "Hello, world!");
62
+ /// # Ok(())
63
+ /// # }
64
+ /// ```
65
+ ///
66
+ /// It can be more efficient to read the contents of a file with a buffered
67
+ /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
68
+ ///
69
+ /// ```no_run
70
+ /// use std::fs::File;
71
+ /// use std::io::BufReader;
72
+ /// use std::io::prelude::*;
45
73
///
46
- /// let mut f = try!(File::open("foo.txt"));
47
- /// let mut s = String::new();
48
- /// try!(f.read_to_string(&mut s));
49
- /// assert_eq!(s, "Hello, world!");
74
+ /// # fn foo() -> std::io::Result<()> {
75
+ /// let file = try!(File::open("foo.txt"));
76
+ /// let mut buf_reader = BufReader::new(file);
77
+ /// let mut contents = String::new();
78
+ /// try!(buf_reader.read_to_string(&mut contents));
79
+ /// assert_eq!(contents, "Hello, world!");
50
80
/// # Ok(())
51
81
/// # }
52
82
/// ```
83
+ ///
84
+ /// [`BufReader`]: ../io/struct.BufReader.html
53
85
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
54
86
pub struct File {
55
87
inner : fs_imp:: File ,
0 commit comments