Writing to files is done using the ofstream (output file stream) class. This class allows you to create new files or overwrite existing ones and write various types of data, including strings, integers, and more. It also supports formatting the output before writing it to a file.
ofstream to Write to a FileThe ofstream class is used to open files for writing. You can either specify the file name when creating the ofstream object or use the open() method to open an existing file. If the file does not exist, it will be created. If it already exists, its contents will be overwritten unless you use the append mode (ios::app).
Here’s a basic example of how to open a file and write to it:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("example.txt"); // Open file for writing
if (!outfile) {
cout << "Error opening file for writing!" << endl;
return 1;
}
outfile << "Hello, World!" << endl; // Writing a string to the file
outfile.close(); // Don't forget to close the file
return 0;
}
In this example:
ofstream outfile("example.txt"): Opens the file example.txt for writing.outfile << "Hello, World!": Writes the string "Hello, World!" to the file.outfile.close(): Closes the file once done.Just like in standard output (using cout), you can use the stream insertion operator (<<) to write data to a file. Here’s how to write various types of data to a file:
You can write plain strings to a file by passing them to the output stream object:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
string text = "This is a string.";
outfile << text << endl; // Writing a string to the file
outfile.close();
return 0;
}
You can write numeric data (like integers or floating-point numbers) using the << operator. The same approach works for other data types such as double or float.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
int number = 42;
outfile << "The number is: " << number << endl; // Writing an integer
double pi = 3.14159;
outfile << "The value of pi is: " << pi << endl; // Writing a floating-point number
outfile.close();
return 0;
}
You can mix different types of data in a single output operation:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
string name = "Alice";
int age = 25;
double height = 5.7;
// Write multiple types of data to the file
outfile << "Name: " << name << endl;
outfile << "Age: " << age << endl;
outfile << "Height: " << height << " meters" << endl;
outfile.close();
return 0;
}
This will output the following content to example.txt:
Name: Alice
Age: 25
Height: 5.7 meters
C++ allows you to format output when writing to a file, just as you would with cout. You can control the formatting of numbers, set precision for floating-point values, align text, etc.
setw() for Setting WidthThe setw() function, from the <iomanip> library, allows you to set the width of the output. This is useful when you want to align numbers or strings.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
outfile << setw(10) << "Number" << setw(15) << "Squared" << endl;
for (int i = 1; i <= 5; ++i) {
outfile << setw(10) << i << setw(15) << i * i << endl; // Aligned columns
}
outfile.close();
return 0;
}
This will output:
Number Squared
1 1
2 4
3 9
4 16
5 25
setprecision() for Controlling Decimal PlacesYou can use setprecision() to control the number of digits displayed after the decimal point for floating-point numbers:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
double pi = 3.1415926535;
// Write pi with different precision
outfile << fixed << setprecision(2) << pi << endl; // 3.14
outfile << fixed << setprecision(4) << pi << endl; // 3.1416
outfile << fixed << setprecision(6) << pi << endl; // 3.141593
outfile.close();
return 0;
}
The output will be:
3.14
3.1416
3.141593
endl for New LinesJust like cout, you can use endl to insert a newline character. It also flushes the output buffer, ensuring that the data is immediately written to the file:
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
outfile << "Line 1" << endl; // Writing with a newline
outfile << "Line 2" << endl;
outfile << "Line 3" << endl;
outfile.close();
By default, opening a file with ofstream will overwrite its contents. If you want to append to a file (i.e., add data to the end of the file without overwriting the existing content), you need to use the ios::app mode:
ofstream outfile("example.txt", ios::app); // Open for appending
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
outfile << "Appending some more text." << endl;
outfile.close();
It’s always a good practice to check for errors when writing to a file. You can check if the file stream is in a good state using the fail() method:
ofstream outfile("example.txt");
if (!outfile) {
cout << "Error opening file!" << endl;
return 1;
}
outfile << "Writing some data" << endl;
if (outfile.fail()) {
cout << "Error occurred during file write!" << endl;
}
outfile.close();
ofstream, and you can write strings, integers, floating-point numbers, and more.setw() for setting width, setprecision() for controlling decimal places, and endl for inserting newlines.