当前位置: 首页 > 文档资料 > 通过例子学 Rust >

文件输入输出 I/O - 创建文件 create

优质
小牛编辑
132浏览
2023-12-01

create 静态方法以只写模式(write-only mode)打开一个文件。若文件已经存在,则旧内容将被销毁。否则,将创建一个新文件。

  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. // 以只写模式打开文件,返回 `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. // 将 `LOREM_IPSUM` 字符串写进 `file`,返回 `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. }

下面是预期成功的输出:

  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.

(和前面例子一样,我们鼓励你在失败条件下测试这个例子。)

还有一个更通用的 open_mode 方法,这能够以其他方式来来打开文件,如:read+write(读+写),追加(append),等等。