Skip to content

Commit db3636f

Browse files
authored
Merge pull request #1186 from AndyGauge/file-read-lines
File read lines
2 parents 7775157 + 6e44483 commit db3636f

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@
184184
- [File I/O](std_misc/file.md)
185185
- [`open`](std_misc/file/open.md)
186186
- [`create`](std_misc/file/create.md)
187+
- [`read lines`](std_misc/file/read_lines.md)
187188
- [Child processes](std_misc/process.md)
188189
- [Pipes](std_misc/process/pipe.md)
189190
- [Wait](std_misc/process/wait.md)

src/std_misc/file/read_lines.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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.

0 commit comments

Comments
 (0)