私は、実行可能ファイルが置かれているディレクトリのconfigフォルダからファイルを読みたいと思っています。私は、以下の機能を使用していることを実行します。現在の実行可能ファイルのパスのディレクトリ部分だけを取得するには?
私の場合はuse std::env;
// add part of path to te path gotten from fn get_exe_path();
fn get_file_path(path_to_file: &str) -> PathBuf {
let final_path = match get_exe_path() {
Ok(mut path) => {
path.push(path_to_file);
path
}
Err(err) => panic!("Path does not exists"),
};
final_path
}
// Get path to current executable
fn get_exe_path() -> Result<PathBuf, io::Error> {
//std::env::current_exe()
env::current_exe()
}
、get_exe_path()
はC:\Users\User\Documents\Rust\Hangman\target\debug\Hangman.exe
を返します。
get_file_path("Config\test.txt")
で、私はConfig\test.txt
を上記のパスに追加したいと思います。ファイルに次のパスが表示されます。C:\Users\User\Documents\Rust\Hangman\target\debug\Hangman.exe\Config\test.txt
問題は、std::env::current_exe()
は実行可能ファイルのファイル名も取得するため、その必要はありません。私はそれが置かれているディレクトリだけが必要です。
質問
次以下の関数呼び出しがC:\Users\User\Documents\Rust\Hangman\target\debug\Config\test.txt
を返す必要があります:
let path = get_file_path("Config\\test.txt");
私は上記の例のように実行可能ファイル名なしでカレントディレクトリからのパスを取得できますか? std::env::current_exe()
私はほんの少しより多くのメモリが効率的だ別のバージョンを追加しました@TimonPost。 – Shepmaster