Files, arguments and environment variables
A useful command-line program almost always does three things: it receives arguments when launched, it reads or writes files and it communicates with the user (and with other programs) through the output and the exit code. This lesson brings together the standard library pieces you need for the final project: std::env for arguments and environment variables, std::fs for files, std::io for input and output, and std::process to finish with an error code.
Command-line arguments
std::env::args() returns an iterator with the arguments. The first one (index 0) is the program name, so the real arguments start at the second. The usual thing is to collect them into a Vec<String> with collect. With cargo run, you pass arguments to the program after two dashes: cargo run -- word file.txt, so that cargo does not confuse them with its own. Always validate that the needed arguments are there and show a clear usage message if they are missing, instead of letting the program panic from an out-of-range index.
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("args.len() = {}", args.len());
// skip(1) ignores the program name
let user_args: Vec<&String> = args.iter().skip(1).collect();
println!("user arguments: {:?}", user_args);
match user_args.first() {
Some(first) => println!("first argument: {first}"),
None => println!("usage: program <word> <file>"),
}
// environment variables return a Result
let verbose = env::var("VERBOSE_RUST_COURSE").is_ok();
println!("verbose = {verbose}");
}Reading and writing files
For small files, fs::read_to_string(path) reads the whole content into a String and fs::write(path, content) writes it, creating the file or replacing it. Both return io::Result, so the ? operator fits perfectly. For large files, do not load everything in memory: open the file with File::open, wrap it in a BufReader and walk the lines with lines(), which are an iterator of Result<String>. To append to the end of an existing file you use OpenOptions with append(true). Paths can be &str, String or Path.
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
fn main() -> io::Result<()> {
let mut path = std::env::temp_dir();
path.push("rust_course_demo.txt");
fs::write(&path, "first line\nsecond line\nthird line\n")?;
let mut file = OpenOptions::new().append(true).open(&path)?;
writeln!(file, "fourth line")?;
let whole = fs::read_to_string(&path)?;
println!("{} bytes, {} lines", whole.len(), whole.lines().count());
let reader = BufReader::new(File::open(&path)?);
for (i, line) in reader.lines().enumerate() {
let line = line?;
if line.contains("o") {
println!("{}: {}", i + 1, line);
}
}
match fs::read_to_string("this_file_does_not_exist.txt") {
Ok(_) => println!("unexpected"),
Err(e) => println!("expected error: {}", e.kind() == io::ErrorKind::NotFound),
}
fs::remove_file(&path)?;
Ok(())
}Standard output, standard error and exit code
A good command-line program separates two channels: println! writes to standard output (stdout), where the useful result goes that other programs can redirect to a file or another tool; eprintln! writes to standard error (stderr), where error and usage messages go. That way, if the user runs program > result.txt, errors still appear on screen and are not mixed with the data. Also, with std::process::exit(code) you finish with a non-zero code when something fails, so scripts and tools can detect it.
use std::process;
struct Config {
word: String,
path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
Ok(Config { word: args[1].clone(), path: args[2].clone() })
}
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
eprintln!("usage: program <word> <file>");
process::exit(2);
});
println!("searching '{}' in {}", config.word, config.path);
}use std::{env, fs, process};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("usage: wc_lite <file>");
process::exit(2);
}
let text = match fs::read_to_string(&args[1]) {
Ok(t) => t,
Err(e) => {
eprintln!("cannot read {}: {e}", args[1]);
process::exit(1);
}
};
println!(
"{} lines, {} words, {} bytes",
text.lines().count(),
text.split_whitespace().count(),
text.len()
);
}Teste dein Wissen
Frage 1 von 4What does args[0] contain in std::env::args()?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen