HOWTO · C++
How to Write to File in C++
This article demonstrates how to write to a file in C++. Learn about file streams, different file modes, and see clear examples to effectively manage file operations in your C++ programs. Whether you need to append data or overwrite existing content, this guide has you covered.
On this page
Use std::ofstream with the insertion operator (<<) to write ordinary text to a file. Open with std::ios::app to add data at the end, or use std::ios::trunc when you want to replace existing contents. For a known number of characters or bytes, use a stream’s write member function; fwrite is the corresponding C-style alternative.
Understanding File Streams in C++
File streams connect a C++ program to a named file. Include <fstream> and create a std::ofstream for output; use std::fstream when the same stream needs both input and output. The insertion operator is convenient for formatted text, and a newline in the string starts another line in the file. Check the stream after opening and writing, since a valid-looking path may still be inaccessible or its storage may be unavailable.
Run this example:
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt");
if (!file) {
std::cerr << "Could not open example.txt\n";
return 1;
}
file << "Hello, C++!\n";
file << "File output is ready.\n";
file.close();
if (!file) {
std::cerr << "Could not finish writing example.txt\n";
return 1;
}
std::cout << "Wrote example.txt\n";
return 0;
}
Wrote example.txt
The message is printed to the console; the two lines written through file are stored in example.txt. Open that file in a text editor to inspect its contents. A default output-only std::ofstream creates the file when its parent directory exists and normally clears an existing file as it opens it.
Writing to Files in Different Modes
Opening mode controls what happens to existing data. std::ios::app positions each write at the end of the file, which is useful for logs or records that should accumulate. If the file does not exist, opening it for output can create it when the path and permissions allow. The following standalone example writes one line in append mode; it does not require an existing example.txt.
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt", std::ios::app);
if (!file) {
std::cerr << "Could not open example.txt\n";
return 1;
}
file << "A new log entry\n";
file.close();
if (!file) {
std::cerr << "Could not finish writing example.txt\n";
return 1;
}
return 0;
}
The supplied runtime case completed successfully and produced no console output. The code writes A new log entry followed by a newline; if the file already contains data, the new line follows it.
Writing and Overwriting Files with ios::trunc
std::ios::trunc discards a file’s previous contents when it is opened. Opening a std::ofstream for output without std::ios::app normally has the same truncating effect, so specify std::ios::trunc when making that choice explicit. Do not use either form when the old data must be retained.
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("example.txt", std::ios::trunc);
if (!file) {
std::cerr << "Could not open example.txt\n";
return 1;
}
file << "Current report\n";
file.close();
if (!file) {
std::cerr << "Could not finish writing example.txt\n";
return 1;
}
return 0;
}
The supplied runtime case completed successfully and produced no console output. The code writes only Current report and a newline to example.txt, replacing any prior contents.
Write to a File with fstream::write
Use the stream member function write when the data is already in a character buffer and its length is known. It takes a character pointer and a count of characters to write; it does not add a terminator or newline for you. The count is a stream size, so passing data.size() writes the string’s stored characters without including a trailing null character. Check the stream after the call to detect a failed write. See the cppreference documentation for basic_ostream::write for its interface.
#include <fstream>
#include <iostream>
#include <string>
int main() {
const std::string data = "C++ buffer data\n";
std::fstream file("buffer.txt", std::ios::out | std::ios::trunc);
if (!file) {
std::cerr << "Could not open buffer.txt\n";
return 1;
}
file.write(data.data(), static_cast<std::streamsize>(data.size()));
if (!file) {
std::cerr << "Could not write buffer.txt\n";
return 1;
}
file.close();
if (!file) {
std::cerr << "Could not finish writing buffer.txt\n";
return 1;
}
return 0;
}
The supplied runtime case completed successfully and produced no console output. It writes the characters in data to buffer.txt; the newline is part of the string, while no trailing null character is written.
Character writes and byte writes differ in whether the data is formatted. The insertion operator converts values into text, while write and fwrite copy the buffer’s bytes without formatting them. Copying bytes alone does not guarantee they reach the file unchanged: a stream opened in text mode can still translate newline characters on platforms that use a different line ending, such as Windows converting \n to \r\n on output. When the exact bytes matter, open the stream in binary mode, for example with std::ios::out | std::ios::binary | std::ios::trunc, or pass "wb" instead of "w" to fopen, so that no translation takes place.
Write to a File with the C fwrite Function
For C-style file I/O, fwrite accepts a pointer, an element size, an element count, and a FILE*. Its return value is the number of elements written, not the number of bytes unless each element has size one. Check that count, then close the file and check fclose as well, because buffered write errors can surface during closing.
#include <cstdio>
#include <cstring>
#include <iostream>
int main() {
const char data[] = "C file output\n";
const std::size_t size = std::strlen(data);
std::FILE* file = std::fopen("c-output.txt", "w");
if (file == nullptr) {
std::cerr << "Could not open c-output.txt\n";
return 1;
}
const std::size_t written = std::fwrite(data, 1, size, file);
const int close_status = std::fclose(file);
if (written != size || close_status != 0) {
std::cerr << "Could not finish writing c-output.txt\n";
return 1;
}
return 0;
}
The supplied runtime case completed successfully and produced no console output. The code writes the characters in data, including its newline, to c-output.txt; the "w" mode creates the file or truncates its prior contents.
Conclusion
For ordinary text, use std::ofstream and <<. Choose std::ios::app to retain old contents and add at the end, or std::ios::trunc to replace them. Use write for a buffer with a known length, and use fwrite when working with C-style I/O. Check open and write state, and check close errors when the program needs to know that data was fully written.
FAQ
-
How can I tell whether a file opened? Check the stream directly (
if (!file)) or callis_open()immediately after opening. Handle failure before writing. -
How do I append without replacing existing contents? Open an output stream with
std::ios::app. Each write is directed to the end of the file. -
Will C++ create a file that does not exist? Output streams and
fopenwith mode"w"can create it if the parent directory exists and the process has permission. A missing parent directory or insufficient permission causes opening to fail. -
How do I write multiple lines? Insert newline characters with
<<, or include them in the buffer passed towrite. Neitherwritenorfwriteadds line endings automatically. -
Should I close the file? A file stream closes when it is destroyed, but explicitly calling
close()can make the point of completion clear. Check stream state after closing when write completion matters. For CFILE*, callfcloseand check its return value.