2

I want to open a file, but in the case that my program fails to open it I want to print an error message to the user and exit early.

use std::fs::File;

fn main() {
    let file = "something.txt";
    let file = match File::open(file) {
        Ok(val) => val,
        Err(e) => {
            //err_string is not a real function, what would you use?
            println!("failed to open file: {}", e.err_string());
            return;
        }
    };
}
1

2 Answers 2

5

you can just do:

println!("failed to open file: {}", e);

it will convert it to a string automatically

Sign up to request clarification or add additional context in comments.

Comments

2

Print an error message to the user and exit early:
1. You may use File::open("something.txt")?, try the following example (No panic, just print an error message):


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

fn main() -> std::io::Result<()> {
    let mut file = File::open("something.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}

Output (on error):

Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }

  1. Using .expect("msg"): Panics if the value is an Err, with a panic message including the passed message, and the content of the Err (developer friendly, since shows the file name and line number):
use std::fs::File;
use std::io::prelude::*;

fn main() {
    let mut file = File::open("something.txt").expect("failed to open file");
    let mut contents = String::new();
    file.read_to_string(&mut contents)
        .expect("failed to read file");
    assert_eq!(contents, "Hello, world!");
}

Output (on error):

thread 'main' panicked at 'failed to open file: 
Os { code: 2, kind: NotFound, message: "No such file or directory" }', 
src/main.rs:17:20
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

  1. No panic, just print an error message:
use std::fs::File;
use std::io::prelude::*;

fn main() {
    let mut file = match File::open("something.txt") {
        Ok(val) => val,
        Err(e) => {
            println!("failed to open file: {}", e);
            return;
        }
    };

    let mut contents = String::new();
    file.read_to_string(&mut contents)
        .expect("failed to read file");
    assert_eq!(contents, "Hello, world!");
}

Output (on error):

failed to open file: No such file or directory (os error 2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.