]>
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 | |
8 | static LOREM_IPSUM: &'static str = | |
9 | "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
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; | |
18 | use std::io::prelude::*; | |
19 | use std::fs::File; | |
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) { | |
28 | Err(why) => panic!("couldn't create {}: {}", | |
29 | display, | |
30 | why.description()), | |
31 | Ok(file) => file, | |
32 | }; | |
33 | ||
34 | // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>` | |
35 | match file.write_all(LOREM_IPSUM.as_bytes()) { | |
36 | Err(why) => { | |
37 | panic!("couldn't write to {}: {}", display, | |
38 | why.description()) | |
39 | }, | |
40 | Ok(_) => println!("successfully wrote to {}", display), | |
41 | } | |
42 | } | |
43 | ``` | |
44 | ||
45 | Here's the expected successful output: | |
46 | ||
47 | ```bash | |
48 | $ mkdir out | |
49 | $ rustc create.rs && ./create | |
50 | successfully wrote to out/lorem_ipsum.txt | |
51 | $ cat out/lorem_ipsum.txt | |
52 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod | |
53 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
54 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo | |
55 | consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse | |
56 | cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non | |
57 | proident, sunt in culpa qui officia deserunt mollit anim id est laborum. | |
58 | ``` | |
59 | ||
60 | (As in the previous example, you are encouraged to test this example under | |
61 | failure conditions.) | |
62 | ||
63 | There is also a more generic `open_mode` method that can open files in other | |
64 | modes like: read+write, append, etc. |