Skip to content

Commit

Permalink
Merge pull request #1186 from AndyGauge/file-read-lines
Browse files Browse the repository at this point in the history
File read lines
  • Loading branch information
marioidival committed Apr 26, 2019
2 parents 7775157 + 6e44483 commit db3636f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
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
44 changes: 44 additions & 0 deletions src/std_misc/file/read_lines.md
@@ -0,0 +1,44 @@
# 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 prints 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 than creating a `String` in memory
especially working with larger files.

0 comments on commit db3636f

Please sign in to comment.