|
|||||
ファイル読み込みテキストファイルを1行ずつ読み込む。 File::open()でファイルをオープンしたら、BufReaderで包んで1行ずつ読み込む。std::io::prelude::*をuseする必要があることがすこぶる分かりにくかったが、恐らくこれにBufReadトレイトが含まれているのだろう。
use std::fs::File;
// std::io::prelude::*が必要という事が分かりにくかった
use std::io::prelude::*;
use std::io::BufReader;
fn main() {
let file = File::open("test.txt").unwrap();
let reader = BufReader::new(file);
// ファイルから1行ずつ読み込む
for line in reader.lines() {
println!("{}", line.unwrap());
}
}
cargo runする際、"test.txt"はプロジェクトディレクトリ(Cargo.tomlのあるディレクトリ)に配置しておいた。 (2021/01/20)
Copyright© 2004-2021 モバイル開発系(K) All rights reserved.
[Home]
|
|||||