file - 如何仅获取当前可执行文件路径的目录部分?

标签 file path directory rust

我想从可执行文件所在目录的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()之外,还有其他方法可以做到这一点

最佳答案

PathBuf::pop PathBuf::push的镜像:

Truncates self to self.parent.

Returns false and does nothing if self.file_name is None. Otherwise, returns true.



在您的情况下:
use std::env;
use std::io;
use std::path::PathBuf;

fn inner_main() -> io::Result<PathBuf> {
    let mut dir = env::current_exe()?;
    dir.pop();
    dir.push("Config");
    dir.push("test.txt");
    Ok(dir)
}

fn main() {
    let path = inner_main().expect("Couldn't");
    println!("{}", path.display());
}

也有可能使用 Path::parent :

Returns the Path without its final component, if there is one.

Returns None if the path terminates in a root or prefix.



在您的情况下:
fn inner_main() -> io::Result<PathBuf> {
    let exe = env::current_exe()?;
    let dir = exe.parent().expect("Executable must be in some directory");
    let mut dir = dir.join("Config");
    dir.push("test.txt");
    Ok(dir)
}

也可以看看:
  • How to get the name of current program without the directory part?
  • 关于file - 如何仅获取当前可执行文件路径的目录部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66528510/

    相关文章:

    linux - 从一个位置开始将一个长字符串包装成多行

    algorithm - 寻找最低成本路径的非有向图算法

    node.js - 如何获取正在运行的 Yeoman 生成器的当前路径

    java - 如何在 Android 的根文件夹中创建文件夹

    powershell - 使用更好的 PowerShell 脚本将文件应用到多个文件夹

    file - C程序如何写入文本文件

    ruby-on-rails - Ruby 文件复制生成不同的文件

    path - 无法打开包含文件 "jni.h",不存在这样的文件或目录

    c - 使用c中的文件路径打开文件

    C++文件输出只接受第一个字