📜  Rust-文件输入/输出

📅  最后修改于: 2020-11-02 04:22:46             🧑  作者: Mango


除了对控制台进行读写之外,Rust还允许对文件进行读写。

File结构代表一个文件。它允许程序对文件执行读写操作。 File结构中的所有方法都返回io :: Result枚举的变体。

下表列出了File结构的常用方法-

Sr.No Module Method Signature Description
1 std::fs::File open() pub fn open(path: P) -> Result The open static method can be used to open a file in read-only mode.
2 std::fs::File create() pub fn create(path: P) -> Result 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.
3 std::fs::remove_file remove_file() pub fn remove_file(path: P) -> Result<()> Removes a file from the filesystem. There is no guarantee that the file is immediately deleted.
4 std::fs::OpenOptions append() pub fn append(&mut self, append: bool) -> &mut OpenOptions Sets the option for the append mode of file.
5 std::io::Writes write_all() fn write_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this write.
6 std::io::Read read_to_string() fn read_to_string(&mut self, buf: &mut String) -> Result Reads all bytes until EOF in this source, appending them to buf.

写入文件

让我们看一个示例,以了解如何编写文件。

以下程序创建文件“ data.txt”。 create()方法用于创建文件。如果文件创建成功,则该方法返回文件句柄。最后一行write_all函数将在新创建的文件中写入字节。如果任何操作失败,则Expect()函数将返回错误消息。

use std::io::Write;
fn main() {
   let mut file = std::fs::File::create("data.txt").expect("create failed");
   file.write_all("Hello World".as_bytes()).expect("write failed");
   file.write_all("\nTutorialsPoint".as_bytes()).expect("write failed");
   println!("data written to file" );
}

输出

data written to file

从文件读取

以下程序读取data.txt文件中的内容,并将其打印到控制台。 “打开”函数用于打开现有文件。文件的绝对或相对路径作为参数传递给open()函数。如果文件不存在或由于某种原因无法访问,则open()函数将引发异常。如果成功,则将该文件的文件句柄分配给“ file”变量。

“文件”句柄的“ read_to_string”函数用于将该文件的内容读入字符串变量。

use std::io::Read;

fn main(){
   let mut file = std::fs::File::open("data.txt").unwrap();
   let mut contents = String::new();
   file.read_to_string(&mut contents).unwrap();
   print!("{}", contents);
}

输出

Hello World
TutorialsPoint

删除档案

下面的示例使用remove_file()函数删除文件。如果发生错误,expect()函数将返回自定义消息。

use std::fs;
fn main() {
   fs::remove_file("data.txt").expect("could not remove file");
   println!("file is removed");
}

输出

file is removed

将数据附加到文件

append()函数将数据写入文件的末尾。这在下面给出的示例中显示-

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
   let mut file = OpenOptions::new().append(true).open("data.txt").expect(
      "cannot open file");
   file.write_all("Hello World".as_bytes()).expect("write failed");
   file.write_all("\nTutorialsPoint".as_bytes()).expect("write failed");
   println!("file append success");
}

输出

file append success

复制文件

以下示例将文件中的内容复制到新文件。

use std::io::Read;
use std::io::Write;

fn main() {
   let mut command_line: std::env::Args = std::env::args();
   command_line.next().unwrap();
   // skip the executable file name
   // accept the source file
   let source = command_line.next().unwrap();
   // accept the destination file
   let destination = command_line.next().unwrap();
   let mut file_in = std::fs::File::open(source).unwrap();
   let mut file_out = std::fs::File::create(destination).unwrap();
   let mut buffer = [0u8; 4096];
   loop {
      let nbytes = file_in.read(&mut buffer).unwrap();
      file_out.write(&buffer[..nbytes]).unwrap();
      if nbytes < buffer.len() { break; }
   }
}

main.exe data.txt datacopy.txt的身份执行上述程序。执行文件时传递了两个命令行参数-

  • 源文件的路径
  • 目标文件