Caution
お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。
std::fs::read_to_string() / write()
Rustの『std::fs』モジュールには、ファイルの読み書きを1行で行える簡易関数『read_to_string()』『write()』『read()』が用意されています。小さなファイルの読み書きに便利で、『?』演算子とセットで使います。
構文
use std::fs;
// ファイル全体をStringとして読み込みます。
let content: String = fs::read_to_string("path/to/file.txt")?;
// ファイル全体をバイト列(Vec<u8>)として読み込みます。
let bytes: Vec<u8> = fs::read("path/to/file.bin")?;
// 文字列をファイルに書き込みます(上書き。ファイルがなければ作成します)。
fs::write("output.txt", "Hello, Rust!\n")?;
// バイト列をファイルに書き込みます。
fs::write("output.bin", &[0u8, 1, 2, 3])?;
// ファイルをコピーします。
fs::copy("src.txt", "dst.txt")?;
// ファイルを削除します。
fs::remove_file("file.txt")?;
// ディレクトリを作成します(途中のディレクトリも含めて作成します)。
fs::create_dir_all("path/to/dir")?;
関数一覧
| 関数 | 概要 |
|---|---|
| fs::read_to_string(path) | ファイル全体を UTF-8 文字列として読み込みます。Result<String> を返します。 |
| fs::read(path) | ファイル全体をバイト列として読み込みます。Result<Vec<u8>> を返します。 |
| fs::write(path, data) | データをファイルに書き込みます(上書き)。Result<()> を返します。 |
| fs::copy(from, to) | ファイルをコピーします。コピーしたバイト数を返します。 |
| fs::rename(from, to) | ファイルを移動・リネームします。 |
| fs::remove_file(path) | ファイルを削除します。 |
| fs::remove_dir(path) | 空のディレクトリを削除します。 |
| fs::remove_dir_all(path) | ディレクトリを中身ごと削除します。 |
| fs::create_dir(path) | ディレクトリを1段階作成します。 |
| fs::create_dir_all(path) | 途中のディレクトリも含めて再帰的に作成します。 |
| fs::metadata(path) | ファイルのメタデータ(サイズ・更新日時など)を取得します。 |
サンプルコード
use std::fs;
use std::io;
fn main() -> io::Result<()> {
// ファイルに書き込みます。
fs::write("hello.txt", "Hello, Rust!\nファイル書き込みテストです。\n")?;
println!("hello.txt に書き込みました");
// ファイルを読み込みます。
let content = fs::read_to_string("hello.txt")?;
println!("読み込み内容:\n{}", content);
// バイト列として読み込みます。
let bytes = fs::read("hello.txt")?;
println!("ファイルサイズ: {} バイト", bytes.len());
// ファイルをコピーします。
fs::copy("hello.txt", "hello_copy.txt")?;
println!("hello_copy.txt にコピーしました");
// メタデータを取得します。
let meta = fs::metadata("hello.txt")?;
println!("サイズ: {} バイト", meta.len());
println!("読み取り専用: {}", meta.permissions().readonly());
// ディレクトリを作成します。
fs::create_dir_all("test/nested/dir")?;
println!("ディレクトリを作成しました");
// ディレクトリにファイルを書き込みます。
fs::write("test/nested/dir/data.txt", "ネストしたファイル")?;
// 後片付け
fs::remove_file("hello_copy.txt")?;
fs::remove_dir_all("test")?;
fs::remove_file("hello.txt")?;
println!("クリーンアップ完了");
Ok(())
}
概要
『fs::read_to_string()』と『fs::write()』は小さなファイルの読み書きに最適な関数です。どちらも『Result』を返すため、『?』演算子でエラーを上位に伝播できます。
大きなファイルや行ごとの処理が必要な場合は『File::open()』と『BufReader』を使うと効率的です。詳細はFile::open() / File::create()を参照してください。
注意: 『fs::write()』は既存ファイルを上書きします。追記したい場合は『OpenOptions::new().append(true)』を使ってください。ファイルパスの操作についてはstd::path::Path / PathBufも参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。