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
fs::read_to_string reads files into strings.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the file-io category to build a complete understanding of this topic.