How to handle a stream of files in rust?

Asked 2 days ago
Viewed 7 times

My goal is to have my cli program accept a stream of files

eg. Directory example_data has the following files

  • a.txt
  • b.txt
  • c.txt

I would like my rust program to handle something like the following

cargo run < example_data/*.txt

Is this type of setup possible? What's an alternative to this? I don't want to have to pass the file names individually to the program. Any suggestions?

asked 2 days ago

Correct Answer

If you can call your program with *.txt, the shell will pass multiple arguments to your program. You can access program arguments in Rust via std::env::args:

> cargo run *.txt
fn main() {
    for arg in std::env::args().skip(1) {
        println!("arg: {}", arg);
arg: a.txt
arg: b.txt
arg: c.txt

You can then process the file names as you wish.

answered 2 days ago