Silent crash from fs::read_to_string(f).expect("..")

Hi,

I'm pretty new to Rust and has been very impressed so far.
However, I just came across the following:

fs::read_to_string(filename).expect("couldn't read file");

When filename points to a non-existing file. My program silently dies with no output.
It took me quite a while to figure out that it was the expect call that seemed to cause it.
Not until I ran 'cargo valgrind' did I get a printout complaining about this string.
So am I doing something wrong here or why didn't the expect message show up ?

Using rustc 1.60 on a Linux machine.

That definitely shouldn't happen in debug mode, unless you're redirecting stderr to /dev/null.

1 Like

For this code:

fn main() {
    let _ = std::fs::read_to_string("filename").expect("couldn't read file");
}

you should have more or less exactly this output with cargo run:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.74s
     Running `target/debug/playground`
thread 'main' panicked at 'couldn't read file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:2:49
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

How are you running your binary ? What's the exact command invoked ?

1 Like

I ran my program as: cargo run -- test.txt
where test.txt is a filename I was getting as an input argument.

Since I'm playing around with the tui-rs package where I've written a simple
'less' application as an exercise, I wanted to be able to read in a new file
to be displayed, and while I was debugging the UI, I typed in some garbage characters,
i.e which later lead to a non-existing file.

Well, the code can be found here: myless/ui.rs at main · etnt/myless · GitHub
line 205 in ui.rs has now been changed so that it won't crash again.

My guess is tui-rs is somehow causing the error message to be swallowed up - undoubtedly it messes around with terminal control attributes.

Yes, that seem like a plausible reason.
Thanks!