Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine files with cat using Rust

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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("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("Failure");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading