Read and write to file in C++

By , last updated October 8, 2016

Many C++ developers find themselves in a place where they need to store information in an external file, which they can retrieve later to perform the operation based on the values. For instance, they have created a video game which has a high score system, wherein top 5 highest scores need to be saved in a file, as information saved in memory in real-time gets deleted once the program is turned off, so they would pursue a fast way to store their values in the external source.

One of the most commonly used file formats to store such information is a binary file format, also know as .ini, .dat files, etc. These are the formats where values are binded to the unique keys, and optionally separated within different sections to ease the organization, i.e., id and password key in id section, sfx and music key in the audio section, etc. C++ has grown both in its popularity and the features with new versions (i.e., C++11/C++14). However, we don’t find much information on reading/writing values in a text file, and the needs often get neglected, due to large database availability, but still the potential of a small text file for some tasks can not be ignored.

In this article, I am going to show you how you can utilize the built-in APIs in C++ to read/write the text files. Let’s get started!

C++ read file

C++ uses file streams for text processing. When you use << and >> operator on std::cout and std::cin to print and read things on screen, you are actually passing/retrieving the values from the I/O streams. In order to create a text file and read from it, you need to first attach the stream to a file. In C++, the usual stream classes for file system are ofstream (output file stream) and ifstream (input file stream). An additional type called an fstream is provided which allows for files that can be written to and read from if this is a desirable property (in the design of database type programs, this is often the case).

Read also  Replace string in XML file with Python

Let's create the file called "myfile.txt" through an ifstream stream. You must open the file for creating the file, in order to any operation on it, and then you must close the file to prevent memory leak:

int main() {
	std::string filename = "myfile.txt";
	std::ifstream in(filename, std::ios::out);
	in.open();
	in.close();
}

In order to read all the contents in a text file, we need to run the while loop till we find the line in a text, meaning when the content is ended:

int main() {
	std::string filename = "myfile.txt";
	std::ifstream in(filename, std::ios::out);
	if (!in.is_open()) {
		std::cerr << "Error: Unable to open settings file \"" << filename << "\" for reading!" << std::endl;
		return false;
	}

	std::string line;
	while (std::getline(in, line)) {
		std::cout << line;
	}

	in.close();
}

In the constructor of std::ifstream, the first parameter is the name of file, the second is the specified option to denote the nature of the operation. We have many options: ios::in, ios::out, ios::ate, ios::trunc, ios::binary. You can read about them from here (http://www.cplusplus.com/reference/ios/ios_base/openmode/).

C++ write to file

In order to write something in a text file in C++, we need to use std::ofstream stream. The steps to do so are quite similar to reading the file:

int main() {
	std::string filename = "myfile.txt";
	std::ofstream  out(filename, std::ios::out);
	out << "Richard";
	out .close();
}

Here, we are using an operator on "out" to write the contents of our file stream. You can even write the contents after reading the file, but you need to print the old values again in the stream, as creating a stream with a same name overrides the content:

int main() {
	std::string filename = "myfile.txt";
	std::ifstream in(filename, std::ios::out);
	if (!in.is_open()) {
		std::cerr << "Error: Unable to open settings file \"" << filename << "\" for reading!" << std::endl;
		return false;
	}

	std::string line;
	while (std::getline(in, line)) {
		std::cout << line;
	}

	in.close();
	std::ofstream  out(filename, std::ios::out);
	out << line;
	out << "Richard";
	out.close();
	std::cin.get();
}

(Note: You need to include , and library to run the provided examples)
Now, you can easily read and write useful values in an external text file. But, what if you need to store values in unique keys?

Read also  Error: anachronistic old-style base class initializer

Help libraries

There is a library (https://github.com/Foaly/SettingsParser) in Github community, which seamlessly combines both the writing and reading text file power into a simple library, which takes advantage of the new features of C++11. This creates a .ini file, which has unique keys that take values, which can be string, integers and booleans. Instead of writing your own library, I recommend using the SettingParser.

For the simple tasks such as storing integer, boolean and string values which aren't very big, then it is highly recommended to use the .ini file system. However, if your needs for storing/retrieving values do not fit the system boundary, i.e., you want the keys to have relationships with other keys and different operations, then you might need to look into other formats, such as, XML, Database integration, etc. to your program.

If you have any question, then ask in the comment section below!

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*