如何设置环境变量以读取可执行文件中指定的文件路径?

huangapple go评论71阅读模式
英文:

How to make environment variable to read the filepath specified in an executable?

问题

以下是翻译好的部分:

我的源代码如下所示:

use std::env;
use std::fs;

fn main() {
    let args: Vec<String> = env::args().collect();

    let file = &args[1];

    let fileContent = fs::read_to_string("./".to_owned() + file).expect("文件找不到");
    println!("文件内容:{}\n", fileContent);

    let a = std::io::stdin().read_line(&mut String::new()).unwrap();
}

该代码是用Rust编程语言编写的,用于创建一个命令行界面程序。

由于在Rust中,可执行文件位于/target/debug/目录中,我可以在环境变量中设置可执行文件的完整路径,使用一个名为CLI_RUST的变量名,这样我就可以从本地文件层次结构的任何位置调用可执行文件。

问题是,当我尝试在除了二进制文件的确切目录之外的任何位置调用.exe文件时,环境能够执行该二进制文件,但找不到二进制文件中指定的文件。我已经尝试使用文件的完整路径来从二进制文件中读取它,但仍然会引发异常。唯一成功的情况是当我进入二进制文件的确切目录时,它才能按预期工作。

那么,如何解决这个问题呢?

英文:

So my source code look like this:

use std::env;
use std::fs;

fn main() {
    let args: Vec&lt;String&gt; = env::args().collect();

    let file = &amp;args[1];

    let fileContent = fs::read_to_string(&quot;./&quot;.to_owned() + file).expect(&quot;file cannot be found&quot;);
    println!(&quot;File content: {}\n&quot;, fileContent);

    let a = std::io::stdin().read_line(&amp;mut String::new()).unwrap();
}

the code is written in Rust programming language to make a command line interface program.

Since, in Rust the executable is inside the /target/debug/ directory, I can set the full path of the executable in the environment variable, with a name called CLI_RUST, so that I can call the executable from anywhere of my local file hierarchy.

The problem is, when I tried to invoke the .exe file anywhere except the exact directory of the binary, the environment is able to execute that binary but could not find the file specified in the binary (.exe) file.

I already tried the full path of .txt file to be read from the binary but still it throws exception. Only success is when I enter the exact directory of the binary, then it will work as intended.

So how to overcome this?

答案1

得分: 1

我的完整路径定义是不正确的,我应该在我的绝对文件路径字符串末尾添加 \\,因为之后我想将它附加到一个文件名上。

例如:

c:\\global\\first\\second\\.to_owned()+file;

而不仅仅是:

c:\\global\\first\\second.to_owned()+file;

因为这是我最初写的,我以为它会是完整的路径。

英文:

Indeed, my full path definition is incorrect, I should add the \\ at the end of my absolute file path string, because later I want to append it to a file name.

for example:

c:\\global\\first\\second\\.to_owned()+file;

instead of just:

c:\\global\\first\\second.to_owned()+file;

Because this is what I initially written by me thought it would be the full path.

huangapple
  • 本文由 发表于 2023年7月24日 17:26:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定