File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 11# ` read_lines `
22
3+ ## Beginner friendly method
4+ This method is NOT efficient. It's here for beginners
5+ who can't understand the efficient method yet.
6+
7+ ``` rust,no_run
8+ use std::fs::File;
9+ use std::io::{ self, BufRead, BufReader };
10+
11+ fn read_lines(filename: String) -> io::Lines<BufReader<File>> {
12+ // Open the file in read-only mode.
13+ let file = File::open(filename).unwrap();
14+ // Read the file line by line, and return an iterator of the lines of the file.
15+ return io::BufReader::new(file).lines();
16+ }
17+
18+ fn main() {
19+ // Stores the iterator of lines of the file in lines variable.
20+ let lines = read_lines("./hosts".to_string());
21+ // Iterate over the lines of the file, and in this case print them.
22+ for line in lines {
23+ println!("{}", line.unwrap());
24+ }
25+ }
26+ ```
27+
28+ Running this program simply prints the lines individually.
29+ ``` shell
30+ $ echo -e " 127.0.0.1\n192.168.0.1\n" > hosts
31+ $ rustc read_lines.rs && ./read_lines
32+ 127.0.0.1
33+ 192.168.0.1
34+ ```
35+
36+ ## Efficient method
337The method ` lines() ` returns an iterator over the lines
438of a file.
539
You can’t perform that action at this time.
0 commit comments