rust之std::env获取当前工作路径、修改当前工作路径的代码如下:
use std::{env,fs};
fn fmtpath()->std::io::Result<()>{
println!("---------------------------------------------");
let p = env::current_dir()?;
println!("1.当前的工作路径是 {:?}", p.display());
//println!("当前工作路径是 {:?}", p);
// let p:String=p.display().to_string()+"\\src";
// println!("现在的工作路径是 {:?}", p);
let p:String=String::from("src");//"src\\mymod"
std::env::set_current_dir(p).unwrap();//设置改变工作路径
let p=env::current_dir()?;
println!("2.现在的工作路径是 {:?}", p.display().to_string());
let p:String=String::from("../");// ../表示当前路径的上一级路径;./则表示当前路径
std::env::set_current_dir(p).unwrap();//设置改变工作路径
let p=env::current_dir()?;
println!("3.现在的工作路径是 {:?}", p.display().to_string());
let p:String=String::from("../");
std::env::set_current_dir(p).unwrap();//设置改变工作路径
let p=env::current_dir()?;
println!("4.现在的工作路径是 {:?}", p.display().to_string());
let p:String=String::from("../");
std::env::set_current_dir(p).unwrap();//设置改变工作路径
let p=env::current_dir()?;
println!("5.现在的工作路径是 {:?}", p.display().to_string());
Ok(())
}
/*如上代码输出的内容是
---------------------------------------------
1.当前的工作路径是 "D:\\MyRustProject\\test1"
2.现在的工作路径是 "D:\\MyRustProject\\test1\\src"
3.现在的工作路径是 "D:\\MyRustProject\\test1"
4.现在的工作路径是 "D:\\MyRustProject"
5.现在的工作路径是 "D:\\"
*/
知识拓展:
// 获取构建模式
// let profile = env::var("PROFILE").unwrap();
// println!("{:?}",profile);
//此此失败,不知道为什么
// let dir = env::temp_dir();
// println!("Temporary directory: {}", dir.display());
//Temporary directory: C:\Users\ADMINI~1\AppData\Local\Temp\
// let path = env::current_dir().unwrap();
// println!("The current directory is {}", path.display());
//The current directory is F:\MyRustProject\test1
// match env::current_exe() {
// Ok(exe_path) => println!("Path of this executable is: {}",exe_path.display()),
// Err(e) => println!("failed to get current exe path: {e}"),
// };
//Path of this executable is: F:\MyRustProject\test1\target\debug\test1.exe
// match env::home_dir() {
// Some(path) => println!("Your home directory, probably: {}", path.display()),
// None => println!("Impossible to get your home dir!"),
// }
//Your home directory, probably: C:\Users\Administrator
// for argument in env::args() {
// println!("{argument}");
// }
//target\debug\test1.exe