You are currently viewing C++ Programming 101: How to Write Text to a File

C++ Programming 101: How to Write Text to a File

In C++, writing text to a file is an essential skill that enables you to store and manipulate data efficiently. Whether you’re building a data logging application, generating reports, or simply storing user input, knowing how to write text to a file is a fundamental task. In this blog post, we will explore how to write text to a file in C++.

This code creates a file called “memo.txt” and writes three lines of text to it using an ofstream object. If the file cannot be created or opened for writing, an error message is printed to the standard error stream.

The code opens the file in output mode, which creates the file if it doesn’t exist, or truncates it to zero length if it does exist. It then uses the insertion operator “<<” to write the lines of text to the file, followed by an endline character. Finally, it closes the file using the close() method of the ofstream object.

#include <iostream>
#include <fstream>
#include <cstring>

int main() 
{

    std::string filename = "memo.txt";

    /* open or create file 'memo.txt' */
    std::ofstream output{filename};

    if (output.fail())
    {
        std::cerr << "Error: " << std::strerror(errno) << std::endl;
        return 1;
    }

    /* write lines of text to file */
    output << "Line 1" << std::endl;
    output << "Line 2" << std::endl;
    output << "Line 3" << std::endl;

    /* close file */
    output.close();

    std::cout << "Text written to file " << filename << "." << std::endl;

    return 0;

}

The code is simple and easy to understand, and it provides feedback to the user when the operation is complete. I hope that’s been informative to you. If you wish to learn more about C++, please subscribe to our newsletter today and continue your C++ learning journey with us!