Fs::read_to_string() saying file not found even when file exists

Hi i am new to rust. Trying to implement the minigrep present in The book .
My program is given below.

use std::env;
use std::fs;
use std::process;
#[allow(dead_code)]
struct Config {
    filename: String,
    pattern: String,
}


fn extractargs(arg: Option<String>) -> Result<String, &'static str> {
    match arg {
        Some(value) => Ok(value),
        None => Err("insufficient parameters"),
    }
}

fn capture_args(args: &mut Vec<String>) -> Result<Config, Box<dyn std::error::Error>> {
    let pat = extractargs(args.pop())?;
    let file = extractargs(args.pop())?;
    Ok(Config {
        filename: file,
        pattern: pat,
    })
}

fn main() {
    let mut args: Vec<String> = env::args().skip(1).collect();
    let config = match capture_args(&mut args) {
        Ok(config) => config,
        Err(e) => {
            println!("{}", e);
            process::exit(1)
        }
    };
    println!(
        "Present working directory of exe {}",
        env::current_dir().unwrap().display()
    );
    let content = fs::read_to_string(config.filename).unwrap();
    println!("{content}");
}

My user directory looks something as shown below

minigrep
|----> src
|---->file.txt
|----->cargo.lock
|------>cargo.toml

I am running the cargo from the root folder minigrep

cargo build
cargo run path file.txt

But for some reason that is unknown to me the program says file not found.
Error message

Present working directory of exe C:\01_somename\UT_Training\minigrep
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\main.rs:40:55
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\minigrep.exe path file.txt` (exit code: 101)

what am i doing wrong ?
Request the help of the community.
Many thanks.

The Vec::pop function returns the last element of the vector. Not the first one. You're trying to open a file called path.

2 Likes