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