]> git.proxmox.com Git - rustc.git/blame - src/doc/book/src/ch12-02-reading-a-file.md
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / doc / book / src / ch12-02-reading-a-file.md
CommitLineData
13cf67c4
XL
1## Reading a File
2
3Now we’ll add functionality to read the file that is specified in the
4`filename` command line argument. First, we need a sample file to test it with:
5the best kind of file to use to make sure `minigrep` is working is one with a
6small amount of text over multiple lines with some repeated words. Listing 12-3
7has an Emily Dickinson poem that will work well! Create a file called
8*poem.txt* at the root level of your project, and enter the poem “I’m Nobody!
9Who are you?”
10
11<span class="filename">Filename: poem.txt</span>
12
13```text
74b04a01 14{{#include ../listings/ch12-an-io-project/listing-12-03/poem.txt}}
13cf67c4
XL
15```
16
17<span class="caption">Listing 12-3: A poem by Emily Dickinson makes a good test
18case</span>
19
20With the text in place, edit *src/main.rs* and add code to read the file, as
9fa01778 21shown in Listing 12-4.
13cf67c4
XL
22
23<span class="filename">Filename: src/main.rs</span>
24
6a06907d 25```rust,should_panic,noplayground
74b04a01 26{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-04/src/main.rs:here}}
13cf67c4
XL
27```
28
29<span class="caption">Listing 12-4: Reading the contents of the file specified
30by the second argument</span>
31
32First, we add another `use` statement to bring in a relevant part of the
33standard library: we need `std::fs` to handle files.
34
9fa01778 35In `main`, we’ve added a new statement: `fs::read_to_string` takes the
532ac7d7 36`filename`, opens that file, and returns a `Result<String>` of the file’s
9fa01778 37contents.
13cf67c4 38
9fa01778 39After that statement, we’ve again added a temporary `println!` statement that
13cf67c4
XL
40prints the value of `contents` after the file is read, so we can check that the
41program is working so far.
42
43Let’s run this code with any string as the first command line argument (because
44we haven’t implemented the searching part yet) and the *poem.txt* file as the
45second argument:
46
f035d41b 47```console
74b04a01 48{{#rustdoc_include ../listings/ch12-an-io-project/listing-12-04/output.txt}}
13cf67c4
XL
49```
50
51Great! The code read and then printed the contents of the file. But the code
52has a few flaws. The `main` function has multiple responsibilities: generally,
53functions are clearer and easier to maintain if each function is responsible
54for only one idea. The other problem is that we’re not handling errors as well
55as we could. The program is still small, so these flaws aren’t a big problem,
56but as the program grows, it will be harder to fix them cleanly. It’s good
57practice to begin refactoring early on when developing a program, because it’s
58much easier to refactor smaller amounts of code. We’ll do that next.