'Combine files with cat
I am trying to combine files with cat using Rust. Below is some example code that is erroring with the below error.
use std::process::Command as cmd;
cmd::new("/bin/cat")
.arg("1.txt 2.txt > 3.txt")
.spawn()
.expect("Failure");
/bin/cat: '1.txt 2.txt > 3.txt': No such file or directory
I also tried adding it as multiple arguments with
cmd::new("/bin/cat")
.args("1.txt 2.txt", ">", "3.txt")
.spawn()
.expect("Failure");
which errors out with
/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
I've tried with cmd::new("/bin/sh") but that doesn't work either.
Solution 1:[1]
Here are two examples considering the suggestions in the comments.
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())
.spawn()
.expect("spawn 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"])
.spawn()
.expect("spawn failure")
.wait()
.expect("wait failure");
}
Solution 2:[2]
A simpler and more robust solution is to use std::fs instead of 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");
Note that this doesn't depend on cat, it works on every platform and operating system, and it allows handling each error properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Aloso |
