Reading from files with streams
Now that we know how to write to a file using streams, we will learn how to read a file using streams. In this recipe, we will write a similar program to that of the previous recipe. But this time, we will read line by line from a file instead and print it to stdout.
Mastering both the writing and reading of streams will enable you to do many things in Linux.
Getting ready
All you need for this recipe is listed under the Technical requirements section of this chapter.
How to do it…
Here we will write a program that will be very similar to the previous recipe, but it will read text from a file instead. The principle of the program is the same as the previous recipe:
- Write the following code in a file and save it as
stream-read.c
. Notice how similar this program is. We have changed write mode ("w"
) to read mode ("r"
) when opening the stream withfopen()
. In thewhile
loop, we read from the file pointer...