intermediateFile I/O
File Read
Read files with std::fs.
File Read
Read files with std::fs.
Difficulty
Intermediate
Code
rust
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// read entire file
let content = fs::read_to_string("Cargo.toml")?;
println!("first line: {}", content.lines().next().unwrap_or(""));
// read bytes
let bytes = fs::read("Cargo.toml")?;
println!("file size: {} bytes", bytes.len());
Ok(())
}Explanation
This example demonstrates how to use file read in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the file-io category to build a complete understanding of this topic.