create

The create static method opens a file in write-only mode. If the file
already existed, the old content is destroyed. Otherwise, a new file is
created.

  1. static LOREM_IPSUM: &'static str =
  2. "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  3. tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
  4. quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  5. consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
  6. cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
  7. proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  8. ";
  9. use std::error::Error;
  10. use std::io::prelude::*;
  11. use std::fs::File;
  12. use std::path::Path;
  13. fn main() {
  14. let path = Path::new("out/lorem_ipsum.txt");
  15. let display = path.display();
  16. // Open a file in write-only mode, returns `io::Result<File>`
  17. let mut file = match File::create(&path) {
  18. Err(why) => panic!("couldn't create {}: {}",
  19. display,
  20. why.description()),
  21. Ok(file) => file,
  22. };
  23. // Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>`
  24. match file.write_all(LOREM_IPSUM.as_bytes()) {
  25. Err(why) => {
  26. panic!("couldn't write to {}: {}", display,
  27. why.description())
  28. },
  29. Ok(_) => println!("successfully wrote to {}", display),
  30. }
  31. }

Here’s the expected successful output:

  1. $ mkdir out
  2. $ rustc create.rs && ./create
  3. successfully wrote to out/lorem_ipsum.txt
  4. $ cat out/lorem_ipsum.txt
  5. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  6. tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
  7. quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  8. consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
  9. cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
  10. proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

(As in the previous example, you are encouraged to test this example under
failure conditions.)

There is also a more generic open_mode method that can open files in other
modes like: read+write, append, etc.