Reading a file
- Rust course
- Intermediate
- Lesson 89/115
- 4 min
Read a file with std::fs::read_to_string.
Reading files
The shortest way to read a whole file as text is std::fs::read_to_string. The file might not exist or might not be UTF-8, so it returns io::Result<String>:
use std::fs;
use std::io;
fn main() -> io::Result<()> {
let icerik = fs::read_to_string("notlar.txt")?;
println!("{} satır", icerik.lines().count());
Ok(())
}Having main return io::Result<()> lets you use ?; on error the program exits with a message and a non-zero code.
Paths and the temp folder
Relative paths are resolved against the folder where the program runs. To build paths independent of the platform, Path/PathBuf and join are used. In the exercises we'll work in the temp folder:
use std::env;
use std::path::PathBuf;
let yol: PathBuf = env::temp_dir().join("rust_ders.txt");
println!("{}", yol.display());display() turns the path into a printable form; paths don't always have to be valid UTF-8.
Practice Count lines
Let main return io::Result<()>. Build the path rust_ders.txt in the temp folder, write "elma\narmut\n" with fs::write, read it with fs::read_to_string and print N satır.
Starter code
use std::env;
use std::fs;
use std::io;
fn main() {
// buraya yaz
}Sample solution
use std::env;
use std::fs;
use std::io;
fn main() -> io::Result<()> {
let yol = env::temp_dir().join("rust_ders.txt");
fs::write(&yol, "elma\narmut\n")?;
let icerik = fs::read_to_string(&yol)?;
println!("{} satır", icerik.lines().count());
Ok(())
}Expected output
2 satır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is used to read a binary file (like an image)?
- fs::read_to_string
- fs::open_text
- fs::lines
- fs::read → Vec<u8> Correct answer
Explanation: read_to_string errors on invalid UTF-8; fs::read is used for raw bytes.
2 Read it all
let icerik = fs::____("notlar.txt")?;
let icerik = fs::read_to_string("notlar.txt")?;
Explanation: read_to_string gives the whole file as a String.
3 Function and return
| Term | Meaning |
|---|---|
fs::read_to_string |
io::Result<String> |
fs::read |
io::Result<Vec<u8>> |
env::temp_dir() |
PathBuf |
yol.display() |
Printable path |