Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of current program without the directory part?

Tags:

rust

In Bash this would be ${0##*/}.

use std::env;
use std::path::Path;

fn prog() -> String {
    let prog = env::args().next().unwrap();
    String::from(Path::new(&prog).file_name().unwrap().to_str().unwrap())
}

fn main() {
    println!("{}", prog());
}

Is there a better way? (I particularly dislike those numerous unwrap()s.)

like image 326
vvv Avatar asked Apr 25 '16 18:04

vvv


1 Answers

If you don't care about why you can't get the program name, you can handle all the potential errors with a judicious mix of map and and_then. Additionally, return an Option to indicate possible failure:

use std::env;
use std::path::Path;
use std::ffi::OsStr;

fn prog() -> Option<String> {
    env::args().next()
        .as_ref()
        .map(Path::new)
        .and_then(Path::file_name)
        .and_then(OsStr::to_str)
        .map(String::from)
}

fn main() {
    println!("{:?}", prog());
}

If you wanted to follow delnan's awesome suggestion to use std::env::current_exe (which I just learned about!), replace env::args().next() with env::current_exe().ok().


If you do want to know why you can't get the program name (and knowing why is usually the first step to fixing a problem), then check out ker's answer.

like image 193
Shepmaster Avatar answered Sep 28 '22 00:09

Shepmaster