我试图使用 Rust 将文件与cat
结合起来。是一些示例代码,错误如下。
use std::process::Command as cmd;
cmd::new("/bin/cat")
.arg("1.txt 2.txt > 3.txt")
.s()
.expect("Failure");
/bin/cat:'1.txt 2.txt >3.txt':No such file or directory
我还尝试将其添加为多个参数
cmd::new("/bin/cat")
.args("1.txt 2.txt", ">", "3.txt")
.s()
.expect("Failure");
哪些错误与
/bin/cat: '1.txt 2.txt': No such file or directory
/bin/cat: '>': No such file or directory
/bin/cat: 3.txt: No such file or directory
我试过cmd::new("/bin/sh")
,但这也不起作用。
以下是考虑评论中建议的两个示例。
fn main() {
// redirect output from rust
std::process::Command::new("/bin/cat")
.args(["1.txt", "2.txt"])
.stdout(std::fs::File::create("3.txt").unwrap())
.s()
.expect("s failure")
.wait()
.expect("wait failure");
//
// rely on the shell for redirection
std::process::Command::new("/bin/sh")
.args(["-c", "cat 1.txt 2.txt >3_bis.txt"])
.s()
.expect("s failure")
.wait()
.expect("wait failure");
}
一个更简单,更健壮的解决方案是使用std::fs
而不是cat
:
use std::fs;
let file1 = fs::read_to_string("1.txt").expect("1.txt could not be opened");
let file2 = fs::read_to_string("2.txt").expect("2.txt could not be opened");
fs::write("3.txt", file1 + "\n" + &file2).expect("3.txt could not be written");
请注意,这不依赖于cat
,它适用于每个平台和操作系统,并且它允许正确处理每个错误。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(40条)