How to Write to File in C++
- Understanding File Streams in C++
- Writing to Files in Different Modes
- Writing and Overwriting Files with ios::trunc
-
Use
fstream
andwrite
Function to Write to File -
Use the
fwrite
Function to Write to File - Conclusion
- FAQ

Writing to a file in C++ is a fundamental skill that every programmer should master. Whether you are storing user data, logging events, or saving application settings, knowing how to manipulate files is crucial for creating robust applications.
In this article, we will explore various methods to write to files in C++. We will cover the basics of file handling, delve into different file modes, and provide clear examples to ensure you have a solid understanding. By the end, you’ll be equipped with the knowledge to effectively read from and write to files in your C++ programs. Let’s dive in!
Understanding File Streams in C++
In C++, file handling is accomplished using file streams, which are part of the standard library. The fstream
library provides classes such as ifstream
for reading files and ofstream
for writing files. Before you can write to a file, you need to include the necessary header file and create an instance of the ofstream
class.
Here’s a simple example to demonstrate how to write to a file:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, World!\n";
outFile << "This is a file writing example in C++.\n";
outFile.close();
} else {
std::cerr << "Unable to open file";
}
return 0;
}
In this code, we first include the necessary headers. We create an instance of ofstream
named outFile
and open a file called example.txt
. The is_open()
function checks if the file was successfully opened. If it is, we write two lines of text to the file. Finally, we close the file using close()
. If the file cannot be opened, an error message is displayed.
Output:
The file "example.txt" will contain:
Hello, World!
This is a file writing example in C++.
This simple program illustrates the basics of writing to a file in C++. The next step is to explore different modes of file writing.
Writing to Files in Different Modes
C++ allows you to open files in different modes, which can affect how you write to them. The most common modes are ios::out
, ios::app
, and ios::trunc
. Understanding these modes is essential for effective file handling.
Writing with ios::app
Using the ios::app
mode allows you to append data to the end of an existing file without overwriting its current contents. Here’s an example:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt", std::ios::app);
if (outFile.is_open()) {
outFile << "Appending a new line to the file.\n";
outFile.close();
} else {
std::cerr << "Unable to open file";
}
return 0;
}
In this example, we open example.txt
in append mode. This means that any new data we write will be added after the existing content. As a result, when you run this code, the new line will be appended to the file without removing the previous data.
Output:
The file "example.txt" will now contain:
Hello, World!
This is a file writing example in C++.
Appending a new line to the file.
Using ios::app
is particularly useful when you want to keep a log of events or maintain a history of data entries without losing previous information.
Writing and Overwriting Files with ios::trunc
If you want to overwrite the contents of a file every time you write to it, you can use the ios::trunc
mode. By default, when you open a file with ofstream
, it will truncate the file if it already exists. However, you can explicitly specify this mode if needed.
Here’s how you can do it:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt", std::ios::trunc);
if (outFile.is_open()) {
outFile << "This will overwrite the previous content.\n";
outFile.close();
} else {
std::cerr << "Unable to open file";
}
return 0;
}
In this example, we open example.txt
in truncation mode. This means that any existing content will be erased as soon as the file is opened. When you run this code, the previous lines will be removed, and only the new line will be saved.
Output:
The file "example.txt" will now contain:
This will overwrite the previous content.
Using ios::trunc
is essential when you want to start fresh with a new set of data, ensuring that no old data remains in the file.
Use fstream
and write
Function to Write to File
Another method to write to file is the built-in write
function that can be called from the fstream
object. The write
function takes a character string pointer and the size of the data stored at that address. As a result, given data is inserted into the file associated with the calling stream object.
In the following code sample, we demonstrate the minimal error reporting by printing the status of the open
function call, but in real-world applications, it would require more robust exception handling, which is documented in the manual page.
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::fstream;
using std::ofstream;
using std::string;
int main() {
string text("Some huge text to write to\n");
string filename2("tmp2.txt");
fstream outfile;
outfile.open(filename2, std::ios_base::out);
if (!outfile.is_open()) {
cout << "failed to open " << filename2 << '\n';
} else {
outfile.write(text.data(), text.size());
cout << "Done Writing!" << endl;
}
return EXIT_SUCCESS;
}
Output:
Done Writing!
Use the fwrite
Function to Write to File
Alternatively, we can use fwrite
function from the C-style file I/O
to write to the file. fwrite
obtains the data from the void
pointer and the programmer is responsible for passing the number of items stored at that address as well as the size of each item. The function needs the file stream to be of type FILE*
and that can be obtained by calling the fopen
function.
Notice that fwrite
returns the number of items written to a file when the operation is successful.
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::ofstream;
using std::string;
int main() {
string text("Some huge text to write to\n");
string filename3("tmp3.txt");
FILE *o_file = fopen(filename3.c_str(), "w+");
if (o_file) {
fwrite(text.c_str(), 1, text.size(), o_file);
cout << "Done Writing!" << endl;
}
return EXIT_SUCCESS;
}
Output:
Done Writing!
Conclusion
Writing to files in C++ is a straightforward process that can significantly enhance your programming skills. By understanding file streams and the various modes available, you can effectively manage data storage in your applications. Whether you need to create new files, append data, or overwrite existing content, the techniques outlined in this article will serve as a solid foundation. Practice these examples, and you’ll soon feel confident in your ability to handle file operations in C++. Happy coding!
FAQ
-
How do I check if a file was successfully opened in C++?
You can use theis_open()
method on yourofstream
object to check if the file was successfully opened. -
Can I write to a file without overwriting its contents?
Yes, by using theios::app
mode when opening the file, you can append new data without overwriting existing content.
-
What happens if I try to write to a non-existent file?
If you attempt to write to a non-existent file, C++ will create the file for you, provided you are using theofstream
class. -
How can I write multiple lines to a file in C++?
You can write multiple lines by using the insertion operator (<<
) multiple times, once for each line you want to write. -
Is it necessary to close a file after writing to it?
Yes, it is good practice to close a file after you are done writing to it. This ensures that all data is properly written and resources are freed.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook