Skip to content

Commit 687a1c3

Browse files
authoredNov 12, 2022
Merge pull request #1641 from FritteX14/fixed
Simpler version of the read_lines script.
2 parents 2afa5eb + 2475df9 commit 687a1c3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
 

‎src/std_misc/file/read_lines.md

+34
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,39 @@
11
# `read_lines`
22

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
337
The method `lines()` returns an iterator over the lines
438
of a file.
539

0 commit comments

Comments
 (0)