(E) Line numbering a fileΒΆ

Goal: I will study reading from a text file and writing in it.

Instructions: Create a new project: student/05/line_numbers/.

Create a program that reads a file and writes its contents in another text file while adding the line number and a space at the beginning of each line.

At first, the program asks the user for the specific file for reading and another for writing the text. In case the opening of the input file is successful, this is all the program prints to the screen:

Input file: a.input
Output file: a.output

In case the input file cannot be opened for some reason, the program prints an error message to the user, and the program exits with the return value EXIT_FAILURE:

Input file: not_a_file.input
Output file: a.output
Error! The file not_a_file.input cannot be opened.

If the file a.input contained the following text:

Yogi has a best friend too
Boo Boo, Boo Boo
Yogi has a best friend too
Boo Boo, Boo Boo Bear
Boo Boo, Boo Boo Bear
Boo Boo, Boo Boo Bear
Yogi has a best friend too
Boo Boo, Boo Boo Bear

the program would write the following lines into the file a.output in the first example run:

1 Yogi has a best friend too
2 Boo Boo, Boo Boo
3 Yogi has a best friend too
4 Boo Boo, Boo Boo Bear
5 Boo Boo, Boo Boo Bear
6 Boo Boo, Boo Boo Bear
7 Yogi has a best friend too
8 Boo Boo, Boo Boo Bear

Tips for completing the assignment:

  • Please note that the input file must be stored into the same directory where you execute the program. If you have not changed the default settings, Qt Creator will compile the program into a directory named build-. It is located on the level of the source code directory, and Qt Creator executes the program in the directory in question.

    It is possible to change the execution directory of the program in Qt Creator, but then also the files generated by the compiler go in to this new location, and they can easily end up in version control. It is simplest to copy the input file in the aforementioned directory named build-.

  • You do not have to add the text files you have created into the version control.
  • It is, again, useful to write the program in parts. For example, you can start by making a program that just prints the lines of the file one at a time. After that, you can modify the output by adding the line numbers and, finally, instead of printing on the screen, write the text in a file.
  • Remember that in C++, file handling requires you to include the library fstream at the beginning of the code file.
  • Remember that there are three parts to handling files: opening, writing/reading, and closing. So, do remember to close the files you have opened after your program no longer uses them.

A+ presents the exercise submission form here.