Is this something I should bug report? [solved]


#1

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

Cpuinfo: https://pastebin.com/7T0FhXNd
Code:
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)
}

Output: https://pastebin.com/ZnL1EFby

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


#2

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

https://doc.rust-lang.org/std/option/enum.Option.html#method.expect


#3

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.


#4
  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); 
    std::process::exit(1); 
  }
}

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).


#5

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

https://doc.rust-lang.org/beta/std/fs/fn.read_to_string.html


#6

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


#7

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