Library reference

Read a text file

Save the sample file beside the program. Read the whole file and print the line it contains.

std::fs::read_to_string

Simple example

Read the word saved in the file.

Startinput.txt
Resulthello
input.txt
hello
main.rs
fn main() {
    let text = std::fs::read_to_string("input.txt").expect("Read input.txt");
    println!("{}", text.trim_end());
}
Output
hello
Advertisements

Everyday examples

Read the pickup code that the library saved for the next shift.

Startinput.txt
ResultB12
input.txt
B12
main.rs
fn main() {
    let text = std::fs::read_to_string("input.txt").expect("Read input.txt");
    println!("{}", text.trim_end());
}
Output
B12

Read the room number that the teacher saved for the morning class.

Startinput.txt
ResultRoom 8
input.txt
Room 8
main.rs
fn main() {
    let text = std::fs::read_to_string("input.txt").expect("Read input.txt");
    println!("{}", text.trim_end());
}
Output
Room 8

Show the next stop stored in the bus display file.

Startinput.txt
ResultOak Street
input.txt
Oak Street
main.rs
fn main() {
    let text = std::fs::read_to_string("input.txt").expect("Read input.txt");
    println!("{}", text.trim_end());
}
Output
Oak Street
Run the example
Terminal
rustc main.rs
./main
Official documentation