Examples C++

Append Strings to a File

In this C++ example, we demonstrate how to write and append a series of strings to a file. First, we create an output file object, which has the class type ofstream; The o stands for output, the f stands for file, and stream means that it accepts streams of data. In this case, the stream is a set of characters.

After we create the stream object, we open the file for writing. In general, streams can be opened for reading, writing, or both. Output streams are opened for writing by default. Finally, we write the four cardinal virtues to the file and close it.

After we close the stream, we reopne it in append mode: std::ios_base::app. This mode prevents us from writing over the previoous content in the file. Now, when we write the three theological virtues, they are appended to the end of the file as shown.

And if any one loves righteousness, her labors are virtues; for she teaches self-control and prudence, justice and courage; nothing in life is more profitable for men than these. (Wisdom 8:7)

For now we see in a mirror dimly, but then face to face. Now I know in part; then I shall understand fully, even as I have been fully understood. So faith, hope, love abide, these three; but the greatest of these is love. (1 Corinthians 13:12-13)

Virtues.txt

Fortitude
Prudence
Justice
Temperance
Faith
Hope
Charity
 

main.cpp

#include <iostream>
#include <fstream>

int main() {
	std::cout << "Writing to the file . . ." << std::endl;

	// We will create an output file stream so that we can open it for writing.
	std::ofstream qTextFile;
	// Create a new file or write over an old one.
	qTextFile.open("Virtues.txt");
	// Write the four cardinal virtues to it.
	qTextFile << "Fortitude" << std::endl;
	qTextFile << "Prudence" << std::endl;
	qTextFile << "Justice" << std::endl;
	qTextFile << "Temperance" << std::endl;
	qTextFile.close();

	std::cout << "Appending to the file . . . " << std::endl;
	// Reopen the file to append the theological virtues to it
	qTextFile.open("Virtues.txt", std::ios_base::app);
	qTextFile << "Faith" << std::endl;
	qTextFile << "Hope" << std::endl;
	qTextFile << "Charity" << std::endl;
	qTextFile.close();
	return 0;
}
 

Output

Writing to the file . . .
Appending to the file . . .
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.