Skip to content

Improve the API examples for std::fs::File. #38443

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 24, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 38 additions & 6 deletions src/libstd/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,53 @@ use time::SystemTime;
///
/// # Examples
///
/// Create a new file and write bytes to it:
///
/// ```no_run
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// # fn foo() -> std::io::Result<()> {
/// let mut file = try!(File::create("foo.txt"));
/// try!(file.write_all(b"Hello, world!"));
/// # Ok(())
/// # }
/// ```
///
/// Read the contents of a file into a `String`:
///
/// ```no_run
/// use std::fs::File;
/// use std::io::prelude::*;
///
/// # fn foo() -> std::io::Result<()> {
/// let mut f = try!(File::create("foo.txt"));
/// try!(f.write_all(b"Hello, world!"));
/// let mut file = try!(File::open("foo.txt"));
/// let mut contents = String::new();
/// try!(file.read_to_string(&mut contents));
/// assert_eq!(contents, "Hello, world!");
/// # Ok(())
/// # }
/// ```
///
/// It can be more efficient to read the contents of a file with a buffered
/// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufReader;
/// use std::io::prelude::*;
///
/// let mut f = try!(File::open("foo.txt"));
/// let mut s = String::new();
/// try!(f.read_to_string(&mut s));
/// assert_eq!(s, "Hello, world!");
/// # fn foo() -> std::io::Result<()> {
/// let file = try!(File::open("foo.txt"));
/// let mut buf_reader = BufReader::new(file);
/// let mut contents = String::new();
/// try!(buf_reader.read_to_string(&mut contents));
/// assert_eq!(contents, "Hello, world!");
/// # Ok(())
/// # }
/// ```
///
/// [`BufReader`]: ../io/struct.BufReader.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct File {
inner: fs_imp::File,
Expand Down