]>
Commit | Line | Data |
---|---|---|
416331ca | 1 | # `read_lines` |
48663c56 | 2 | |
6522a427 EL |
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 | |
48663c56 | 37 | The method `lines()` returns an iterator over the lines |
416331ca | 38 | of a file. |
48663c56 XL |
39 | |
40 | `File::open` expects a generic, `AsRef<Path>`. That's what | |
41 | `read_lines()` expects as input. | |
42 | ||
43 | ```rust,no_run | |
44 | use std::fs::File; | |
45 | use std::io::{self, BufRead}; | |
46 | use std::path::Path; | |
47 | ||
48 | fn main() { | |
49 | // File hosts must exist in current path before this produces output | |
50 | if let Ok(lines) = read_lines("./hosts") { | |
51 | // Consumes the iterator, returns an (Optional) String | |
52 | for line in lines { | |
53 | if let Ok(ip) = line { | |
54 | println!("{}", ip); | |
416331ca XL |
55 | } |
56 | } | |
48663c56 XL |
57 | } |
58 | } | |
59 | ||
60 | // The output is wrapped in a Result to allow matching on errors | |
61 | // Returns an Iterator to the Reader of the lines of the file. | |
62 | fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> | |
63 | where P: AsRef<Path>, { | |
64 | let file = File::open(filename)?; | |
65 | Ok(io::BufReader::new(file).lines()) | |
66 | } | |
67 | ``` | |
68 | ||
69 | Running this program simply prints the lines individually. | |
416331ca | 70 | ```shell |
48663c56 XL |
71 | $ echo -e "127.0.0.1\n192.168.0.1\n" > hosts |
72 | $ rustc read_lines.rs && ./read_lines | |
73 | 127.0.0.1 | |
74 | 192.168.0.1 | |
75 | ``` | |
76 | ||
77 | This process is more efficient than creating a `String` in memory | |
78 | especially working with larger files. |