Is this something I should bug report? [solved]

I have this code I shamelessly copied off SO somewhere after fiddling for a few minutes trying to read the contents of a file into a string. Mine was similar to this, but I was not handling a Result somewhere.

Anyways, I was testing it just by reading crontab, and then I decided to read “/etc/cronta” to make sure that it would fail correctly. I was expecting to see “Unable to open file” here, but instead I got a thread panic.

I’m running this on ARMv7, which I’m assuming has something to do with this, so I included cat /proc/cpuinfo

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

// no idea what im doing, honestly

fn main() {
    let mut d = File::open("/etc/cronta").expect("Could not open file.");
    let mut contents = String::new();
    d.read_to_string(&mut contents).expect("Could not read to string.");
    println!("{}", contents)


Thanks in advance. I may be slow answering this thread, but I will answer it!

File::open returns an Option – you’re calling expect which unwraps the option, panicking (with the supplied message) if the Option is None:

I see. I didn’t know expect was doing that, but I recognized it from the book so I didn’t really think about it.

Thanks! I can use a match instead and fix this.

  1. The 3 lines to load a file annoy me so I’ve put them in a crate so that you only need 2 :slight_smile: extern crate file and file::get_text(filename) :slight_smile:

  2. If the program is longer, it’s best to use:

fn main() { 
  if let Err(e) = run_the_rest() { 
    eprintln!("error: {}", e); 

and put code in run_the_rest() -> Result<(), failure::Error> so that you can use ? to handle errors (and failure::Error is a convenient type from the failure crate).

Looks like in 4 days it’ll only take 1:

1 Like

File::open returns a io::Result<File> which is a Result<File, Error> and not an Option.

1 Like

Er, right, of course! Thanks! :slight_smile:

1 Like