Rust - 檔案輸入/輸出



除了讀取和寫入控制檯,Rust 還允許讀取和寫入檔案。

File 結構體表示一個檔案。它允許程式對檔案執行讀寫操作。File 結構體中的所有方法都返回 io::Result 列舉的變體。

File 結構體常用的方法列在下表中:

序號 模組 方法 簽名 描述
1 std::fs::File open() pub fn open<P: AsRef>(path: P) -> Result open 靜態方法可用於以只讀模式開啟檔案。
2 std::fs::File create() pub fn create<P: AsRef>(path: P) -> Result 靜態方法以只寫模式開啟檔案。如果檔案已存在,則舊內容將被銷燬。否則,將建立一個新檔案。
3 std::fs::remove_file remove_file() pub fn remove_file<P: AsRef>(path: P) -> Result<()> 從檔案系統中刪除檔案。不能保證檔案立即被刪除。
4 std::fs::OpenOptions append() pub fn append(&mut self, append: bool) -> &mut OpenOptions 設定檔案的追加模式選項。
5 std::io::Writes write_all() fn write_all(&mut self, buf: &[u8]) -> Result<()> 嘗試將整個緩衝區寫入此寫入器。
6 std::io::Read read_to_string() fn read_to_string(&mut self, buf: &mut String) -> Result 讀取此源中的所有位元組直到 EOF,並將它們追加到 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() 函式。如果檔案不存在,或者由於任何原因無法訪問,open() 函式將丟擲異常。如果成功,則該檔案的控制代碼將賦值給 "file" 變數。

"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`。執行檔案時傳遞兩個命令列引數:

  • 原始檔的路徑
  • 目標檔案
廣告
© . All rights reserved.