]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # `create` |
2 | ||
3 | The `create` static method opens a file in write-only mode. If the file | |
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 | ||
17 | use std::error::Error; | |
2c00a5a8 | 18 | use std::fs::File; |
532ac7d7 | 19 | use std::io::prelude::*; |
2c00a5a8 XL |
20 | use std::path::Path; |
21 | ||
22 | fn 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 | ||
40 | Here's the expected successful output: | |
41 | ||
416331ca | 42 | ```shell |
2c00a5a8 XL |
43 | $ mkdir out |
44 | $ rustc create.rs && ./create | |
45 | successfully wrote to out/lorem_ipsum.txt | |
46 | $ cat out/lorem_ipsum.txt | |
47 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
48 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
49 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
50 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
51 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
52 | proident, 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 | |
56 | failure conditions.) | |
57 | ||
532ac7d7 XL |
58 | There 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 |