]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/std_misc/file/create.md
New upstream version 1.25.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
8static LOREM_IPSUM: &'static str =
9"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
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;
18use std::io::prelude::*;
19use std::fs::File;
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) {
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
45Here's the expected successful output:
46
47```bash
48$ mkdir out
49$ rustc create.rs && ./create
50successfully wrote to out/lorem_ipsum.txt
51$ cat out/lorem_ipsum.txt
52Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
53tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
54quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
55consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
56cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
57proident, 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
61failure conditions.)
62
63There is also a more generic `open_mode` method that can open files in other
64modes like: read+write, append, etc.