LoginSignup
1
2

More than 1 year has passed since last update.

Rustでファイル全体を読み込む方法

Last updated at Posted at 2022-12-29

Rustでファイル全体を読み込む

標準ライブラリのstd::fs::read_to_stringメソッドを使うことにより、ファイル全体を文字列に読み込みます。

std::fs::Filestd::io::Readを用いて次のように書きます。

use std::{fs::File, io::Read};

fn main() {
    let file_name: &str = "src/hoge.xml";
    println!("File name: {}", file_name);

    let mut f: File = File::open(file_name).expect("Fail to open file.");

    let mut contents: String = String::new();
    f.read_to_string(&mut contents).expect("Fail to read file.");

    println!("{}", contents);
}

参考文献

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2