Reading Text Files

Let’s learn about reading text files

In this lesson we will learn how to read plain text files, as well as using the /dev/random UNIX device, which offers us a way of getting random numbers.

Reading a text file line by line

The function for reading a file line by line is found in byLine.go and is named lineByLine(). The technique for reading a text file line by line is also used when reading a plain text file word by word as well as when reading a plain text file character by character because we usually process plain text files line by line. The presented utility prints every line that it reads, which makes it a simplified version of the cat(1) utility.

First, we create a new reader to the desired file using a call to bufio.NewReader(). Then, we use that reader with bufio.ReadString() in order to read the input file line by line. The trick is done by the parameter of bufio.ReadString(), which is a character that tells bufio.ReadString() to keep reading until that character is found. Constantly calling bufio.ReadString() when that parameter is the newline character (\n) results in reading the input file line by line.

Coding example

The implementation of lineByLine() is as follows:

Get hands-on with 1200+ tech skills courses.