Systems Basics
10 examples for processes, files, and OS interaction using Rust's standard library.
Busca en todas las páginas de la documentación
10 examples for processes, files, and OS interaction using Rust's standard library.
Result-based error handlinguse std::fs;
fn main() -> anyhow::Result<()> {
let contents = fs::read_to_string("config.toml")?;
println!("{contents}");
Ok(())
}fs::read_to_string handles UTF-8 decodingstd::io::Errorread for binary datatokio::fs in async applicationsuse std::fs;
fn write_atomically(path: &str, data: &str) -> std::io::Result<()> {
let tmp = format!("{path}.tmp");
fs::write(&tmp, data)?;
fs::rename(&tmp, path)
}rename is atomic on the same filesystemuse std::process::Command;
fn main() -> anyhow::Result<()> {
let output = Command::new("git")
.args(["status", "--short"])
.output()?;
println!("{}", String::from_utf8_lossy(&output.stdout));
Ok(())
}output() waits for completion and captures streamsspawn() returns a Child for background processescurrent_dir and env on the builderstatus.success() before trusting stdoutuse std::env;
fn main() {
for (key, value) in env::vars() {
if key.starts_with("APP_") {
println!("{key}={value}");
}
}
}env::var returns Result for a single variableset_var is unsafe in multithreaded programs (Rust 2024 documents this)use std::fs;
fn main() -> anyhow::Result<()> {
let meta = fs::metadata("Cargo.toml")?;
println!("size: {} bytes", meta.len());
println!("is_dir: {}", meta.is_dir());
Ok(())
}metadata follows symlinks; symlink_metadata does notpermissions() on Unix for mode bitsmodified() returns filesystem timestamps? or matchuse std::fs;
use std::path::Path;
fn list_rs(dir: &Path) -> walkdir::Result<()> {
for entry in walkdir::WalkDir::new(dir) {
let entry = entry?;
if entry.path().extension().is_some_and(|e| e == "rs") {
println!("{}", entry.path().display());
}
}
Ok(())
}walkdir crate simplifies recursive walksWalkDir::new(dir).into_iter().filter_map(|e| e.ok()).gitignore with the ignore crate for toolinguse std::io::{Read, Write};
use std::net::TcpStream;
fn main() -> anyhow::Result<()> {
let mut stream = TcpStream::connect("127.0.0.1:8080")?;
stream.write_all(b"GET /health HTTP/1.0\r\n\r\n")?;
let mut buf = [0u8; 1024];
let n = stream.read(&mut buf)?;
println!("{}", String::from_utf8_lossy(&buf[..n]));
Ok(())
}TcpListener for serverstokio::netread_timeout / write_timeout for resilienceuse std::process::{Command, Stdio};
fn main() -> anyhow::Result<()> {
let mut child = Command::new("grep")
.arg("error")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
child.stdin.as_mut().unwrap().write_all(b"log line\nerror: bad\n")?;
let output = child.wait_with_output()?;
println!("{}", String::from_utf8_lossy(&output.stdout));
Ok(())
}wait or wait_with_output to reap zombiesStdio::null() discards streamsRelated: Signals & Process Control
#[cfg(unix)]
fn make_executable(path: &str) -> anyhow::Result<()> {
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(path)?.permissions();
perms.set_mode(0o755);
std::fs::set_permissions(path, perms)?;
Ok(())
}std::oscfg(unix) / cfg(windows) for portabilityRelated: Cross-Platform Systems Code
use tempfile::NamedTempFile;
fn main() -> anyhow::Result<()> {
let mut tmp = NamedTempFile::new()?;
std::io::Write::write_all(&mut tmp, b"scratch data")?;
let path = tmp.path().to_owned();
// use path; file deleted when `tmp` drops
Ok(())
}tempfile crate handles secure temp pathstempdir() for scratch directories/tmp/myapp-$$ hand-rollingStack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026