পাঠ ১২.২

File পড়া

Reading a File

এখন file path-টা use করে file-এর content পড়ে print করব।

Test file — poem.txt

Project root-এ poem.txt বানাও — Emily Dickinson-এর কবিতা (multi-line, repeated word — search-এর জন্য ভালো test):

poem.txttext
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!

fs::read_to_string

src/main.rsrust
use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let query = &args[1];
    let file_path = &args[2];

    println!("Searching for {query}");
    println!("In file {file_path}");

    let contents = fs::read_to_string(file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}
  • use std::fs — file system module।
  • fs::read_to_string(path) Result<String, io::Error> return করে।
  • .expect(...) — fail হলে message সহ panic।
terminalbash
$ cargo run -- the poem.txt
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
... (পুরো কবিতা)

এই code-এর সমস্যা

কাজ করছে, কিন্তু কয়েকটা issue:

  • main-এ অনেক responsibility — arg parse, file read, print। বড় হলে maintain কঠিন।
  • Error message generic, user-friendly না।
  • Argument count check নেই — missing হলে cryptic panic।

পরের পাঠে refactor করব — modular এবং proper error handling সহ।

এই পাঠ থেকে যা শিখলে

  • fs::read_to_string(path) — পুরো file content একটা String-এ।
  • Return type Result.expect() দিয়ে handle।