]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # `create` |
2 | ||
136023e0 | 3 | The `create` function opens a file in write-only mode. If the file |
2c00a5a8 XL |
4 | already existed, the old content is destroyed. Otherwise, a new file is |
5 | created. | |
6 | ||
7 | ```rust,ignore | |
532ac7d7 XL |
8 | static LOREM_IPSUM: &str = |
9 | "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
2c00a5a8 XL |
10 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, |
11 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
12 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
13 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
14 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum. | |
15 | "; | |
16 | ||
2c00a5a8 | 17 | use std::fs::File; |
532ac7d7 | 18 | use std::io::prelude::*; |
2c00a5a8 XL |
19 | use std::path::Path; |
20 | ||
21 | fn 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 | ||
39 | Here's the expected successful output: | |
40 | ||
416331ca | 41 | ```shell |
2c00a5a8 | 42 | $ rustc create.rs && ./create |
ba9703b0 XL |
43 | successfully wrote to lorem_ipsum.txt |
44 | $ cat lorem_ipsum.txt | |
2c00a5a8 XL |
45 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod |
46 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
47 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
48 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
49 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
50 | proident, 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 | |
54 | failure conditions.) | |
55 | ||
9ffffee4 | 56 | The [`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 |