How to Write Contents to a File in C++


C++


In this article, we show how to write contents to a file in C++.

Writing contents to a blank file will add contents to the file. Writing contents to a file that has contents already will overwrite the contents of that file.

If you don't want to overwrite the contents of a file that has contents but simply append to the file, then you wouldn't write over the file, as explained in this article, but append to it.

This will all be explained.

Below we write contents to a file named file1.txt using C++.

We simply write "Hello" to the file.



We use the library to work with files. In this case, we are writing contents to a file.

We use the library to output an error message if the file, file1.txt, cannot be opened.

We use the library to create a string, which will be the contents of our file that we write to.

We then create our writer object. We use ofstream, instead of ifstream, because we are writing to the object, not reading from it.

We use an if statement to check if the writer object can be successfully opened. If not, we output an error message.

We then use the writer object and write to the file what is in the variable, contents. This is done through the line, writer << contents << endl;

After writing to the file, the writer object must be closed. This is done by the line, writer.close();

This is how you write a single line statement like "Hello" to a file in C++.

Below we do the same but create a more complex write with multi-line statements.

This is shown below.



Now this file write that is more complex, as it contains multiple lines.

Do not get confused by the append() function. You're not appending to the file. You're appending to the write statement that will override everything in the file2.txt file.

We create a string, contents, that contains the text, "Hello"

We then use the append() function to add more lines to the variables, content.

The line, writer << contents << endl;, then writes all the contents of the contents variable to the file2.txt file.

Remember when writing a program like this, be careful. It will completely overwrite everything in the file you are working with. This means everything that is in the file before the write execution will be erased and overwritten.

And this is how to write contents to a file in C++.


Related Resources

How to Append to a File in C++

HTML Comment Box is loading comments...