Not able to open file even though it is there (working with absolute path but not relative path)

here is my code :

use std::fs::File;
use std::io::Read;

fn main() {
let filename = "hello.txt";
let f = File::open(filename);

let mut f = match f {
	Ok(file) => file,
	Err(error) => {panic!("{:?}", error);},

let mut x :String = "".to_sting();
f.read_to_string(&mut x).expect("some error occured");

println!("text was ::::::::: {}", x);


here is the "cargo run " output :

C:\Users\Dell\Desktop\rust\learn\file_io>cargo run
   Compiling file_io v0.1.0 (file:///C:/Users/Dell/Desktop/rust/learn/file_io)
    Finished dev [unoptimized + debuginfo] target(s) in 1.07s
     Running `target\debug\file_io.exe`
thread 'main' panicked at 'Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: process didn't exit successfully: `target\debug\file_io.exe` (exit code: 101)

i can assure you file is present in same directory as binary " C:\Users\Dell\Desktop\rust\learn\file_io\target\debug\hello.txt"

its working when i provide absolute file path , but not with relative path

Have you tried outputting the current directory to see what that actually is for your program? (

Maybe the current directory is the one in which you ran cargo run, which would be pretty normal for the command line. (Double-clicking an exe in explorer sets the current directory to the folder of the executable, but not running it in the command line, or else you couldn’t pass relative paths to things like rg, for example.)


Relative paths are relative to the current working directory, not to the executable. In your case, C:\Users\Dell\Desktop\rust\learn\file_io is the working directory, so it will work if the file is placed there.

1 Like