过去几天我们一直在重新创建 GNU 核心实用程序的基本功能,而今天,我们将做一些有点太简单的事情, pwd
这个实用程序是用于打印Linux终端中的工作目录。
Understanding the utility
了解实用程序
Running the pwd command, we get an output like this
运行 pwd 命令,我们得到如下输出
# pwd
/root/
Here /root
is the directory that we are currently in, in the Linux Shell
这里 /root
是我们当前所在的目录,在 Linux Shell 中
To recreate this, it’s really not difficult and we can recreate this without any trouble using the std::env::current_dir()
function, Let’s create a library crate inside a new Rust project and a module to get started with this.
要重新创建它,实际上并不困难,我们可以使用 std::env::current_dir()
函数毫无困难地重新创建它,让我们在新的 Rust 项目中创建一个库箱和一个模块来开始使用它。
//lib.rs
pub mod dir_get {
use std::env;
use std::path::PathBuf;
fn get_working_directory() -> std::io::Resullt<PathBuf> {
env::current_dir()
}
}
The get_working_directory
function runs the env::current_dir()
function and returns a result enum with a PathBuf
or an Err
variant.get_working_directory
函数运行 env::current_dir()
函数并返回带有 PathBuf
或 Err
变体的结果枚举。
We will do the error handing in the next part…
我们将在下一部分中进行错误处理......
According to the documentation of this ffunction we can see that there are two cases in which this function will return an error:
根据这个ffunction的文档我们可以看到这个函数有两种情况会返回错误:
- Current directory does not exist.
当前目录不存在。 - There are insufficient permissions to access the current directory.
没有足够的权限访问当前目录。
Check out the documentation here :
查看此处的文档:current_dir in std::env - Rust (rust-lang.org)
Now to create a function which prints the PathBuf
while handling the errors :
现在创建一个在处理错误时打印 PathBuf
的函数:
//lib.rs
pub mod dir_get {
use std::env;
use std::path::PathBuf;
fn get_working_directory() -> std::io::Resullt<PathBuf> {
env::current_dir()
}
pub fn print_working_dir() {
let result = get_working_directory();
match result {
Ok(path_buf) => println!("{}",path_buf.as_path().display()),
Err(e) => eprintln!("Application Error: {}",e),
};
}
}
Now that’s all we’ll have to do with the library crate, let’s get to the main.rs
file and call the print_working_dir
function there and check if it works?
现在这就是我们对库箱要做的所有事情,让我们进入 main.rs
文件并调用其中的 print_working_dir
函数并检查它是否有效?
//main.rs
use pwd::dir_get; //use the name of your crate and module here
fn main(){
dir_get::print_working_dir();
}
And it’s done, running the program with cargo run
we get the following response
就完成了,使用 cargo run
运行程序,我们得到以下响应
# pwd #The GNU utility
/root/learning_rust/linux_tools/pwd
# cargo run #The utility that we just built
Finished dev [unoptimized + debuginfo] target(s) in 0.09s
Running `target/debug/pwd`
/root/learning_rust/linux_tools/pwd
Conclusion 结论
Lib.rs :
pub mod dir_get
: This declares a module named dir_get
, which can be accessed from other modules.pub mod dir_get
:这声明了一个名为 dir_get
的模块,可以从其他模块访问该模块。
use std::env;
: This imports theenv
module from the standard library, which provides functions for interacting with the environment variables of the current process.use std::env;
:从标准库导入env
模块,该模块提供与当前进程的环境变量交互的函数。use std::path::PathBuf;
: This imports thePathBuf
struct from thestd::path
module, which represents an owned, mutable path.use std::path::PathBuf;
:这会从std::path
模块导入PathBuf
结构,该结构表示拥有的可变路径。
fn get_working_directory() -> std::io::Result<PathBuf>
: This defines a function named get_working_directory
that returns a result containing a PathBuf
representing the current working directory, wrapped in std::io::Result
.fn get_working_directory() -> std::io::Result<PathBuf>
:这定义了一个名为 get_working_directory
的函数,该函数返回一个结果,其中包含表示当前工作目录的 PathBuf
,包装在 std::io::Result
中。
env::current_dir()
: This is a function from theenv
module that returns aResult<PathBuf, std::io::Error>
representing the current working directory.env::current_dir()
:这是env
模块中的一个函数,它返回表示当前工作目录的Result<PathBuf, std::io::Error>
。
pub fn print_working_dir()
: This defines a public function named print_working_dir
, which takes no arguments.pub fn print_working_dir()
:这定义了一个名为 print_working_dir
的公共函数,它不带任何参数。
let result = get_working_directory();
: This calls theget_working_directory
function and stores the result in theresult
variable.let result = get_working_directory();
:调用get_working_directory
函数并将结果存储在result
变量中。match result { ... }
: This is amatch
expression that handles the result of callingget_working_directory()
. It matches on theOk
variant, which contains the successfully obtainedPathBuf
, and theErr
variant, which contains an error if the operation failed.match result { ... }
:这是一个match
表达式,用于处理调用get_working_directory()
的结果。它与Ok
变体(包含成功获取的PathBuf
)和Err
变体(如果操作失败则包含错误)匹配。Ok(path_buf) => println!("{}", path_buf.as_path().display()),
: Ifget_working_directory()
succeeds, this branch is executed, printing the current working directory usingpath_buf.as_path().display()
.Ok(path_buf) => println!("{}", path_buf.as_path().display()),
:如果get_working_directory()
成功,则执行此分支,并使用path_buf.as_path().display()
打印当前工作目录。Err(e) => eprintln!("Application Error: {}", e),
: Ifget_working_directory()
fails, this branch is executed, printing an error message indicating that an application error occurred.Err(e) => eprintln!("Application Error: {}", e),
:如果get_working_directory()
失败,则执行此分支,打印一条错误消息,指示发生应用程序错误。
Main.rs
use pwd::dir_get;
: This line imports theprint_working_dir
function from thedir_get
module defined in thepwd
crate. This allows us to use the function in the current scope.use pwd::dir_get;
:此行从pwd
包中定义的dir_get
模块导入print_working_dir
函数。这允许我们在当前范围内使用该函数。fn main() { ... }
: This defines the main function, which serves as the entry point of the program.fn main() { ... }
:定义主函数,作为程序的入口点。dir_get::print_working_dir();
: This line calls theprint_working_dir
function from thedir_get
module. It is prefixed withdir_get::
to specify that the function is being called from thedir_get
module.dir_get::print_working_dir();
:此行从dir_get
模块调用print_working_dir
函数。它以dir_get::
为前缀,以指定从dir_get
模块调用该函数。- The
main
function does not take any arguments.main
函数不接受任何参数。 - When executed, this program will print the current working directory to the standard output.
执行时,该程序会将当前工作目录打印到标准输出。 - The
print_working_dir
function is defined in thedir_get
module and is responsible for obtaining and printing the current working directory.print_working_dir
函数定义在dir_get
模块中,负责获取并打印当前工作目录。