Text files

Many practical problems require programs that read data from or write data to files. Data stored in variables and vectors are lost as soon the program ends, i.e. the variables only exist while the program is executing. But, data can be stored permanently in files which usually reside in a hard disk. For instance, consider the example of an app to give information about courses to students. It would not be reasonable that an employee would need to enter manually all information about courses, every time the program would be started. Instead, information about each course can be saved in a file and the app reads that information from the file, whenever needed.

Different types of files can be used to store information: text files and binary files. It’s true that computers store all information in binary mode. So, in this sense, text files are also binary files. The difference between a binary file and a text file is that data in the latter can be converted automaticaly to text form. So, you can open a text file with, for instance, Notepad and make sense out of it. In this course, we only deal with data stored in text files.

A text file is a sequence of lines of text. Each line ends with a special character called new line character (also known as endline character). This character is represented in C++ as '\n'. So, remember that even if you don’t see the new line characters when you open a text file with, for instance Notepad, they are there, in the end of each line.

In C++, like in many other programming languages, programs don’t read and write directly from devices such as hard disks (where files are stored), keyboards, computer screens, etc. Instead, a middle layer of software know as streams is used. Streams are introduced next.