]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/std_misc/file/create.md
New upstream version 1.38.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std_misc / file / create.md
CommitLineData
2c00a5a8
XL
1# `create`
2
3The `create` static method opens a file in write-only mode. If the file
4already existed, the old content is destroyed. Otherwise, a new file is
5created.
6
7```rust,ignore
532ac7d7
XL
8static LOREM_IPSUM: &str =
9 "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
2c00a5a8
XL
10tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
11quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
12consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
13cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
14proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
15";
16
17use std::error::Error;
2c00a5a8 18use std::fs::File;
532ac7d7 19use std::io::prelude::*;
2c00a5a8
XL
20use std::path::Path;
21
22fn main() {
23 let path = Path::new("out/lorem_ipsum.txt");
24 let display = path.display();
25
26 // Open a file in write-only mode, returns `io::Result<File>`
27 let mut file = match File::create(&path) {
532ac7d7 28 Err(why) => panic!("couldn't create {}: {}", display, why.description()),
2c00a5a8
XL
29 Ok(file) => file,
30 };
31
32 // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>`
33 match file.write_all(LOREM_IPSUM.as_bytes()) {
532ac7d7 34 Err(why) => panic!("couldn't write to {}: {}", display, why.description()),
2c00a5a8
XL
35 Ok(_) => println!("successfully wrote to {}", display),
36 }
37}
38```
39
40Here's the expected successful output:
41
416331ca 42```shell
2c00a5a8
XL
43$ mkdir out
44$ rustc create.rs && ./create
45successfully wrote to out/lorem_ipsum.txt
46$ cat out/lorem_ipsum.txt
47Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
48tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
49quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
50consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
51cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
52proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
53```
54
55(As in the previous example, you are encouraged to test this example under
56failure conditions.)
57
532ac7d7
XL
58There is [`OpenOptions`] struct that can be used to configure how a file is opened.
59
60[`OpenOptions`]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html