Wang's blog

十一、标准库 - 其它

Published on

路径

使用std::path中的Path与PathBuf表示系统路径。其中Path是不可变版本,PathBuf为可变版本。

// 建立Path后不可变
let path = Path::new(".");

// 从字符串建立PathBuf
let mut buf = PathBuf::from(".");

// 将Path转换为PathBuf
let mut buf = path.to_path_buf();

// 修改PathBuf
buf.push("a");
buf.push("b.txt");
buf.set_file_name("c.tar");
buf.set_extension("zip");

文件I/O

// 打开文件用于读取
let mut file = File::open(&path).unwrap();

// 读取文件内容到String
let mut s = String::new();
file.read_to_string(&mut s).unwrap();

// 建立文件用于写入
let mut file = File::create(&path).unwrap();

// 将字符串写入文件
file.write_all("content".as_bytes()).unwrap();

子进程

使用std::process::Command执行命令建立子进程。可以使用管道与其交互,等待执行完成并获取返回值。

let output = Command::new("rustc")          // 要执行的命令
.arg("--version")                           // 参数
.output()                                   // 等待执行完毕并获取结果
.unwrap();

let process = Command::new("wc")
.stdin(Stdio::piped())                      // stdin使用管道
.stdout(Stdio::piped())                     // stdout使用管道
.spawn()                                    // 启动命令,不等待执行完毕
.unwrap();

// 写入数据至stdin
process.stdin.unwrap().write_all("content".as_bytes()).unwrap();

// 从stdout读取数据
let mut s = String::new();
process.stdout.unwrap().read_to_string(&mut s).unwrap();

// 等待进程执行完毕
let mut child = Command::new("sleep").arg("5").spawn().unwrap();
child.wait().unwrap();

文件系统操作

fs::create_dir          // 建立目录
fs::create_dir_all      // 建立路径中全部目录
unix::fs::symlink       // 建立软链接
fs::read_dir            // 返回目录下全部文件与目录
fs::remove_file         // 删除文件
fs::remove_dir          // 删除空目录

命令行参数

使用std::env::args()获取所有命令行参数。

外部函数接口(FFI)

Rust提供对C动态库的外部函数接口,外部函数需要在extern块中声明,并使用#[link]属性指定外部库的名称。

// 声明外部函数
#[link(name = "m")]
extern {
    fn csqrtf(z: Complex) -> Complex;
    fn ccosf(z: Complex) -> Complex;
}

// 调用外部函数是unsafe的
let z_sqrt = unsafe { csqrtf(z) };