Rust-file-input-output

提供:Dev Guides
移動先:案内検索

Rust-ファイル入出力

コンソールの読み取りと書き込みに加えて、Rustはファイルの読み取りと書き込みを許可します。

File構造体はファイルを表します。 これにより、プログラムはファイルに対して読み取り/書き込み操作を実行できます。 File構造体のすべてのメソッドは、io
Result列挙のバリアントを返します。

File構造体の一般的に使用されるメソッドは、以下の表に記載されています-

Sr.No Module Method Signature Description
1 std::fs::File open() pub fn open<P: AsRef>(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<P: AsRef>(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<P: AsRef>(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("\nfinddevguides".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
finddevguides

ファイルを削除する

次の例では、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("\nfinddevguides".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_として上記のプログラムを実行します。 ファイルの実行中に2つのコマンドライン引数が渡されます-

  • ソースファイルへのパス
  • 宛先ファイル