Rust编程中的文件操作


文件操作通常包括I/O操作。Rust为我们提供了不同的方法来处理所有这些操作。

打开

Rust提供了一个open静态方法,我们可以用它以只读模式打开一个文件。

示例

考虑下面显示的代码

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
   // Create a path to the desired file
   let path = Path::new("out.txt");
   let display = path.display();
   let mut file = match File::open(&path) {
      Err(why) => panic!("unable to open {}: {}", display, why),
      Ok(file) => file,
   };
   let mut s = String::new();
   match file.read_to_string(&mut s) {
      Err(why) => panic!("unable to read {}: {}", display, why),
      Ok(_) => print!("{} it contains:
{}", display, s),    }    // `file` goes out of scope, and the "out.txt" file gets    closed }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

以上代码的输出是

out.txt contains:
Hello World!

创建

create方法以只写模式打开一个文件,如果文件已经存在,则删除旧内容。

示例

static RANDOM_TEXT: &str = "Lorem ipsum dolor sit AMEN, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
   let path = Path::new("random_text.txt");
   let display = path.display();
   // Open a file in write-only mode, returns `io::Result`
   let mut file = match File::create(&path) {
      Err(why) => panic!("couldn't create {}: {}", display, why),
      Ok(file) => file,
   };
   // Write the `RANDOM_TEXT` string to `file`, returns 
   `io::Result<()>`
   match file.write_all(RANDOM_TEXT.as_bytes()) {
      Err(why) => panic!("couldn't write to {}: {}", display, why),
      Ok(_) => println!("successfully wrote to {}", display),
   }
}

输出

当我们运行以下命令时

cat random_text.txt

我们得到的输出是

Lorem ipsum dolor sit AMEN, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

更新于:2021年4月3日

254次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告