Skip to content

Commit 00e61d4

Browse files
committed
Auto merge of #38443 - frewsxcv:file-docs, r=brson
Improve the API examples for `std::fs::File`. Fixes #35875.
2 parents d86cf13 + a664466 commit 00e61d4

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

Diff for: src/libstd/fs.rs

+38-6
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,53 @@ use time::SystemTime;
3535
///
3636
/// # Examples
3737
///
38+
/// Create a new file and write bytes to it:
39+
///
3840
/// ```no_run
41+
/// use std::fs::File;
3942
/// 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
4054
/// use std::fs::File;
55+
/// use std::io::prelude::*;
4156
///
4257
/// # 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::*;
4573
///
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!");
5080
/// # Ok(())
5181
/// # }
5282
/// ```
83+
///
84+
/// [`BufReader`]: ../io/struct.BufReader.html
5385
#[stable(feature = "rust1", since = "1.0.0")]
5486
pub struct File {
5587
inner: fs_imp::File,

0 commit comments

Comments
 (0)