やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

Rustのファイル読込

 基本のひとつ。

成果物

参考

前回からの続き

  1. Rustでコマンドライン引数を受け取る

コード

use std::env;
use std::fs::File;
use std::io::prelude::*;

fn main() {
    // --snip--
    println!("In file {}", filename);

    // ファイルが見つかりませんでした
    let mut f = File::open(filename).expect("file not found");

    let mut contents = String::new();
    f.read_to_string(&mut contents)
        // ファイルの読み込み中に問題がありました
        .expect("something went wrong reading the file");

    // テキストは\n{}です
    println!("With text:\n{}", contents);
}

poem.txt

  • クレート
    • src/
      • main.rs
      • poem.txt

poem.txt

I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

実行

$ cargo run AAA poem.txt
...
query: AAA
filename: poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

 ファイル読込できた。

標準モジュール

モジュール 概要
std::env; コマンド引数
std::fs::File; ファイルを扱うために必須
std::io::prelude::*; ファイル入出力を含む入出力処理をするのに有用なトレイト群
std::io 入出力を行う際に必要

全コード

use std::env;
use std::fs::File;
use std::io::prelude::*;

fn main() {
    // コマンドライン引数受付
    let args: Vec<String> = std::env::args().collect();
    let query = &args[1];
    let filename = &args[2];
    println!("query: {}", query);
    println!("filename: {}", filename);

    // ファイルが見つかりませんでした
    let mut f = File::open(filename).expect("file not found");

    let mut contents = String::new();
    f.read_to_string(&mut contents)
        // ファイルの読み込み中に問題がありました
        .expect("something went wrong reading the file");

    // テキストは\n{}です
    println!("With text:\n{}", contents);
}

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux

前回まで