英文:
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<String> = env::args().collect();
let file = &args[1];
let fileContent = fs::read_to_string("./".to_owned() + file).expect("file cannot be found");
println!("File content: {}\n", fileContent);
let a = std::io::stdin().read_line(&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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论