]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/std_misc/file/read_lines.md
New upstream version 1.68.2+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std_misc / file / read_lines.md
CommitLineData
416331ca 1# `read_lines`
48663c56 2
6522a427
EL
3## Beginner friendly method
4This method is NOT efficient. It's here for beginners
5who can't understand the efficient method yet.
6
7```rust,no_run
8use std::fs::File;
9use std::io::{ self, BufRead, BufReader };
10
11fn 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
18fn 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
28Running 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
32127.0.0.1
33192.168.0.1
34```
35
36## Efficient method
48663c56 37The method `lines()` returns an iterator over the lines
416331ca 38of a file.
48663c56
XL
39
40`File::open` expects a generic, `AsRef<Path>`. That's what
41`read_lines()` expects as input.
42
43```rust,no_run
44use std::fs::File;
45use std::io::{self, BufRead};
46use std::path::Path;
47
48fn main() {
49 // File hosts must exist in current path before this produces output
50 if let Ok(lines) = read_lines("./hosts") {
51 // Consumes the iterator, returns an (Optional) String
52 for line in lines {
53 if let Ok(ip) = line {
54 println!("{}", ip);
416331ca
XL
55 }
56 }
48663c56
XL
57 }
58}
59
60// The output is wrapped in a Result to allow matching on errors
61// Returns an Iterator to the Reader of the lines of the file.
62fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
63where P: AsRef<Path>, {
64 let file = File::open(filename)?;
65 Ok(io::BufReader::new(file).lines())
66}
67```
68
69Running this program simply prints the lines individually.
416331ca 70```shell
48663c56
XL
71$ echo -e "127.0.0.1\n192.168.0.1\n" > hosts
72$ rustc read_lines.rs && ./read_lines
73127.0.0.1
74192.168.0.1
75```
76
77This process is more efficient than creating a `String` in memory
78especially working with larger files.