Skip to content

Commit

Permalink
example to read a file line by line
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyGauge committed Apr 26, 2019
1 parent 7775157 commit bbf801d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@
- [File I/O](std_misc/file.md)
- [`open`](std_misc/file/open.md)
- [`create`](std_misc/file/create.md)
- [`read lines`](std_misc/file/read_lines.md)
- [Child processes](std_misc/process.md)
- [Pipes](std_misc/process/pipe.md)
- [Wait](std_misc/process/wait.md)
Expand Down
43 changes: 43 additions & 0 deletions src/std_misc/file/read_lines.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Read Lines

The method `lines()` returns an iterator over the lines
of a file.

`File::open` expects a generic, `AsRef<Path>`. That's what
`read_lines()` expects as input.

```rust,no_run
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() {
// File hosts must exist in current path before this produces output
if let Ok(lines) = read_lines("./hosts") {
// Consumes the iterator, returns an (Optional) String
for line in lines {
if let Ok(ip) = line {
println!("{}", ip);
}
}
}
}
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
```

Running this program simply returns the lines individually.
```bash
$ echo -e "127.0.0.1\n192.168.0.1\n" > hosts
$ rustc read_lines.rs && ./read_lines
127.0.0.1
192.168.0.1
```

This process is more efficient that creating a `String` in memory for larger files.

0 comments on commit bbf801d

Please sign in to comment.