Reading a Text File Character by Character

Let’s learn how to read a text file one character at a time.

How to read a text file character by character

In this lesson, we’ll learn how to read a text file character by character, which is a pretty rare requirement unless we want to develop a text editor. We take each line that we read and split it using a for loop with range, which returns two values. We discard the first, which is the location of the current character in the line variable, and we use the second. However, that value is a rune, which means that we have to convert it into a character using string().

Coding example

The implementation of charByChar() is as follows:

Get hands-on with 1400+ tech skills courses.