Skip to content Skip to sidebar Skip to footer

Where to Put a Text File if You Are Calling It in C++

Learning C++: Working with Text Files

Mike McMillan

Photo by David Ballew on Unsplash

C++ has the capability of creating, accessing, and editing text files. In this article I will demonstrate how to do this. I will not be discussing how to work with binary files.

FileStream Objects, Header Files, File Access, and Filenames

C++ uses a file stream abstraction for handling text files. A file stream is data that is either going into a text file to be stored or going out of a text file to be loaded into a program. The input (>>) and the output (<<) operators are used to stream data either into a file or into a program.

To perform file input (receiving data from a file), you must include the ifstream header file in your program. To perform file output (send data to a file) you must include the ofstream header file in your program.

There are two primary ways of accessing files from a program — sequential access and random access. When a file is accessed using random access, the program can move back and forth through the file at random. This means a program can read the first record in a file and then immediately move to the fifth record, or the hundredth record.

When a file is accessed sequentially, on the other hand, the program can only move forward through the file, one record at a time. This means that if you want to read the fifth record in the file, you have to read the first through fourth records first.

Sequential file access is easier to work with than random access so we will be working exclusively with sequential files in this article.

Files are represented on your disk by a file name. Because we are working with text files, the file names should have a .txt extension so the system recognizes them as text files and not some other type of file.

Creating and Storing Data in a Text File

Our first task is to create and store data in a text file. The ofstream library includes a function for creating a new file — open, which takes a string argument consisting of the file name you wan to use.

Files are created in two steps. The first step is to declare the file name and the second step is to call the open function from the new file. Here are the lines needed to create a text file:

          ofstream outFile;
outFile.open("myfile.txt");

The argument to the open function is the full path to the output file you are writing. If you just include the filename, your file will be written in the same file your program resides in. Otherwise, specify a full path before the filename if want the file written somewhere else.

The next step is to write data to the file. Of course, this step will depend on the task you are trying to perform. This next part of the program has the user enter text at a prompt and then writes that data to the file using the file name as the target of the output stream. Here is the code:

          string quit = "n";
string line;
while (quit != "y") {
cout << "Enter a line of text: ";
getline(cin, line);
outFile << line << endl;
cout << "Stop entering text (y/n)? ";
getline(cin, quit);
}

The last step, and an important one, is to close the file. While you probably won't lose data if the program ends before the output file is closed, it is a good programming practice to close files after you are finished with them.

Here is the complete program for creating a file and writing data to that file:

          #include <iostream>
#include <fstream>
using namespace std; int main()
{
ofstream outFile;
outFile.open("myfile.txt");
string quit = "n";
string line;
while (quit != "y") {
cout << "Enter a line of text: ";
getline(cin, line);
outFile << line << endl;
cout << "Stop entering text (y/n)? ";
getline(cin, quit);
}
outFile.close();
return 0;
}

Once you've closed a file you are finished with it until you want to open it in order to read the data from it. I'll cover how to do that in the next section.

Reading Data from a Text File

To read data from a text file, you have to open the file for input. The first thing you need to do is declare an ifstream object to represent an input file. Then you need to open the file by providing the path to the file.

You need to be careful when specifying the file path because if the path has backslashes in it, you have to escape the backslashes so that C++ won't interpret part of the file path as an escaped character.

For example, if the file path includes a \t in the name, C++ will interpret this as the tab character and the system will throw an error. You need to double backslash your paths so that this doesn't happen.

In the example I'm about to show, the file path is:

c:\users\mmcmi\documents\words.txt

Instead, I will write the path like this:

c:\\users\\mmcmi\\documents\\words.txt.

After the file is open, you can loop through the file and read each line. The file object can act as the condition of the loop, meaning that while there is data in the file to read, the file name returns true (1), and when there is no more data to read, the file name returns false (0).

The last step is to close the file to maintain good software engineering practices, though if you don't do this the operating system will close the file automatically.

Now we're ready to view a complete program that reads a text file from a hard disk and displays all the data in the file. The file I'm opening and reading is a dictionary of words.

Here is the program:

          #include <iostream>
#include <fstream>
using namespace std; int main()
{
ifstream inFile;
inFile.open("c:\\users\\mmcmi\\documents\\words.txt");
string word;
while (inFile) {
getline(inFile, word);
cout << word << endl;
}
inFile.close();
return 0;
}

Here is a partial display of the output from this file:

          
bloggers
blogging
blogs
blond
blonde
blood
bloody
bloom
bloomberg
blow
blowing

A more concise way to write the program above is to combine the file check in the condition with getting the next word from the file. Here's how that looks:

          int main()
{
ifstream inFile;
inFile.open("c:\\users\\mmcmi\\documents\\words.txt");
string word;
while (getline(inFile, word)) {
cout << word << endl;
}
inFile.close();
return 0;
}

When the loop reaches the end of the file, getline will essentially return a false value and the loop stops.

Working with Numbers in a Text File

When numbers are stored in a texts file they are stored as strings, so when they are read into a program they have to be converted to the proper numeric data type. Here is an example that reads a set of test grades from a text file and computes the average of the grades:

          #include <iostream>
#include <fstream>
#include <string>
using namespace std; int main()
{
ifstream inFile;
inFile.open("grades.txt");
string strGrade;
int grade, total, numGrades;
total = 0;
numGrades = 0;
while (getline(inFile, strGrade)) {
cout << strGrade << " ";
numGrades++;
grade = stoi(strGrade);
total += grade;
}
inFile.close();
double average = static_cast<double>(total) / numGrades;
cout << endl << endl << "The average test grade is: "
<< average << endl;
return 0;
}

This program uses the stoi function to convert the string grade into an integer.

Working with a file that contains the grades — 82, 91, 77, 84, 91, 63 — the output from this program is:

          82 91 77 84 91 63          The average test grade is: 81.3333        

Appending Data to a File

Besides opening a file for input or output, you can also open a file in order to append new data to it. You do this by adding the constant ios::app as a second argument to the open function. The following program demonstrates how to append data to an existing file of grades, the same file we used in the immediate example above:

          int main()
{
ofstream outFile;
outFile.open("grades.txt", ios::app);
int grade1 = 91;
int grade2 = 87;
int grade3 = 93;
outFile << grade1 << endl;
outFile << grade2 << endl;
outFile << grade3 << endl;
outFile.close();
ifstream inFile;
inFile.open("grades.txt");
int grade;
while (inFile >> grade) {
cout << grade << " ";
}
inFile.close();
return 0;
}

Those are the main points I wanted to cover in this article on working with text files in C++. Please email me at mmmcmillan1@att.net with your comments and suggestions. If you are interested in my online programming courses, please visit https://learningcpp.teachable.com.

Where to Put a Text File if You Are Calling It in C++

Source: https://levelup.gitconnected.com/learning-c-working-with-text-files-91104a8fab33

Post a Comment for "Where to Put a Text File if You Are Calling It in C++"