File tree 2 files changed +45
-0
lines changed 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 184
184
- [ File I/O] ( std_misc/file.md )
185
185
- [ ` open ` ] ( std_misc/file/open.md )
186
186
- [ ` create ` ] ( std_misc/file/create.md )
187
+ - [ ` read lines ` ] ( std_misc/file/read_lines.md )
187
188
- [ Child processes] ( std_misc/process.md )
188
189
- [ Pipes] ( std_misc/process/pipe.md )
189
190
- [ Wait] ( std_misc/process/wait.md )
Original file line number Diff line number Diff line change
1
+ # Read Lines
2
+
3
+ The method ` lines() ` returns an iterator over the lines
4
+ of a file.
5
+
6
+ ` File::open ` expects a generic, ` AsRef<Path> ` . That's what
7
+ ` read_lines() ` expects as input.
8
+
9
+ ``` rust,no_run
10
+ use std::fs::File;
11
+ use std::io::{self, BufRead};
12
+ use std::path::Path;
13
+
14
+ fn main() {
15
+ // File hosts must exist in current path before this produces output
16
+ if let Ok(lines) = read_lines("./hosts") {
17
+ // Consumes the iterator, returns an (Optional) String
18
+ for line in lines {
19
+ if let Ok(ip) = line {
20
+ println!("{}", ip);
21
+ }
22
+ }
23
+ }
24
+ }
25
+
26
+ // The output is wrapped in a Result to allow matching on errors
27
+ // Returns an Iterator to the Reader of the lines of the file.
28
+ fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
29
+ where P: AsRef<Path>, {
30
+ let file = File::open(filename)?;
31
+ Ok(io::BufReader::new(file).lines())
32
+ }
33
+ ```
34
+
35
+ Running this program simply prints the lines individually.
36
+ ``` bash
37
+ $ echo -e " 127.0.0.1\n192.168.0.1\n" > hosts
38
+ $ rustc read_lines.rs && ./read_lines
39
+ 127.0.0.1
40
+ 192.168.0.1
41
+ ```
42
+
43
+ This process is more efficient than creating a ` String ` in memory
44
+ especially working with larger files.
You can’t perform that action at this time.
0 commit comments