2015-11-03 66 views
0

锈病新手在这里。我试图打开一个文件:错误打印当前预期路径

let file = File::open("file.txt").unwrap(); 

由于我的体型设置,它看起来像我的二进制文件和TXT是不是我期望它还是我做错了什么,所以我得到一个:

thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', ../src/libcore/result.rs:736 

错误消息没有说什么txt必须生活的预期路径,以便我的程序和测试看到它。我怎样才能打印这个预期的路径?我想打印这样的消息:

The file "/expected/folder/file.txt" does not exist 

回答

5

只是比赛返回Result明确针对所需错误是这样的:

use std::fs::File; 
use std::io::ErrorKind; 

fn main() { 
    match File::open("file.txt") { 
     Ok(file) => 
      println!("The file is of {} bytes", file.metadata().unwrap().len()), 
     Err(ref e) if e.kind() == ErrorKind::NotFound => 
      println!("The file {}/file.txt does not exist", std::env::current_dir().unwrap().display()), 
     Err(e) => 
      panic!("unexpected error: {:?}", e), 
    } 
} 

playground link

+1

我不能一分钟发现,原来生锈问题或两个搜索,但有人认为,如果文件错误类型应该包括路径或不。如果我没有记错,那就决定不应该包括路径,因为它会比开销更有价值。如图所示,您可以随时添加路径信息。 – Shepmaster