从命令行读取参数
use std::env; fn main() { let args: Vec<String> = env::args().collect(); println!("{:?}", args); }
ai@aisty:/opt/wks/rust/rfil/rcmd/target/debug$ ./rcmd aa bb cc ["./rcmd", "aa", "bb", "cc"]
第一个参数是命令本身
The
args
Function and Invalid UnicodeNote that
std::env::args
will panic if any argument contains invalid Unicode. If your program needs to accept arguments containing invalid Unicode, usestd::env::args_os
instead. That function returns an iterator that producesOsString
values instead ofString
values. We’ve chosen to usestd::env::args
here for simplicity, becauseOsString
values differ per platform and are more complex to work with thanString
values.
use std::env; fn main() { let args: Vec<String> = env::args().collect(); let query = &args[1]; let filename = &args[2]; println!("Searching for {}", query); println!("In file {}", filename); }
ai@aisty:/opt/wks/rust/rfil/rcmd$ cargo run name /tmp/aa.txt Finished dev [unoptimized + debuginfo] target(s) in 0.00s Running `target/debug/rcmd name /tmp/aa.txt` Searching for name In file /tmp/aa.txt
读取指定的文件内容
use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; println!("In file {}", filename); let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); println!("With text:\n{}", contents); }
ai@aisty:/opt/wks/rust/rfil/rcmd$ cargo run /tmp/aa.txt Compiling rcmd v0.1.0 (/opt/wks/rust/rfil/rcmd) Finished dev [unoptimized + debuginfo] target(s) in 0.21s Running `target/debug/rcmd /tmp/aa.txt` In file /tmp/aa.txt With text: aa