Write String to File in C++

Write String to file in C++

The files are used to store the data permanently on a disk. This mitigates the problem of loss of data when the program stops execution. On the other hand, strings are the most common data type to store the text data in C++. This article discusses methods to write string to file in C++.

Using the fstream Library to write String to File in C++

C++ provides an inbuilt library to handle the files. The fstream library is an input and output stream class to handle different operations such as opening, reading, writing, etc on files.

The library provides different ways to write to a file. You can use the insertion operator (<<) with the fstream object to write to a file. Additionally, you can use the write() function to perform the write operation.

Before writing to the file, you must open the file. The open() function of the fstream library accepts the path of the file as an argument and opens the file in the mode provided as the second argument.

The 'mode' defines the operations that you can perform after opening the file. There are six different modes available that you can check out here.

Let us see the definition of the open() function.

If you do not provide any mode, the file opens in the input and output mode.

Let us see the methods of writing to the file using fstream library.

Using the Insertion Operator (<<) With the fstream Object

Once you have created an object of fstream class and opened the file, you can use the object to write to the file using the insertion operator (<<).

It is quite similar to writing to the console except that the fstream object writes to the file unlike cout writing to the console.

Let us see the code.

You may notice that the code checks if the file is open by calling the is_open() function. The is_open() function returns boolean true if the file opens successfully, otherwise, it returns false.

This helps in avoiding the potential program crash in case the file could not be open due to problems such as locks, permissions, disk space, etc.

As a good practice, you should always close the file after use by calling the close() function. However, even if you do not close the file, the destructor automatically closes it.

Output (from the file):

Hi! We are Java2Blog. Follow us for learning more!

Using the write() Function of the fstream Library

The write() function in the fstream library is inherited from the ostream class. Note that you can directly use the ostream class to write to the file. However, this class doesn’t have open() and is_open() function. For this reason, you should prefer the fstream class.

The definition of the write() function is given below.

The method accepts a pointer pointing to an array of characters and the size of the stream. The method then writes the first ‘n’ characters of the array stream to the file.

However, you should be careful as the method does not check the characters of the stream. So if the stream contains null characters, the same is copied to the file.

Let us see the code.

Note that the code uses the data() function on the string object while passing it to the open() function. This is because the open() function accepts the character pointer pointing to the array stream rather than the string object.

The data() function returns a pointer to an array that contains the same characters as the string.

Output (from the file):

Hi! We are Java2Blog. This is example of write method!

Using the fwrite() Function to write String to File in C++

The fwrite() function is the old C-style file handling function. It writes the data from a stream to a file pointed by the FILE pointer.

To write a string to the file using the fwrite() function, it is necessary to have a FILE pointer. Therefore, you must open the file using the fopen() function that returns the FILE pointer.

The fopen() function is similar to the open() function of the fstream class. It accepts the path of the file and the mode of opening the file and returns a FILE pointer. You can read more about it here.

The definition of the fwrite() function is given below.

  • The first parameter ‘ptr’ represents the pointer to the text that the function writes to the file.
  • The ‘size’ represents the size of each block in the ‘ptr’ array.
  • ‘count’ represents the number of ‘size’ blocks to write to the file.
  • And ‘stream’ represents the current position of the FILE stream pointer where the content is written.

Let us see the code.

Output (from the file):

Hi! We are Java2Blog. This is example of fwrite function.


This article discusses three different ways to write a string to a file. All three methods differ in the way they write a string to the file.

However, all of the methods discussed do not implement a strong exception handling mechanism.

Therefore, it is advisable that you should implement your own exception handling mechanism to avoid crashes.

Hope you have enjoyed reading the article. Stay tuned for more articles. Happy Learning!

Was this post helpful?

Related Posts

  • 04 November

    Pass 2D Array to Function in C++

    Table of ContentsWays to Pass a 2D Array to function in C++Pass a 2D Array to a Function by Passing Its PointerPass an Array to the Function by Decaying the Pointer to the ArrayPass a 2D Array to a Function in C++ Without Size by Passing Its ReferenceConclusion Two-dimensional arrays have rows and columns, storing […]

  • 02 November

    Count Decimal Places in C++

    Table of ContentsAccuracy V/S Precision in Counting Decimal Places in C++ ProgramsHow to Count Decimal Places in C++Example 1: Use String Functions to Find Precise Number of Decimal PlacesExample 2: Count Decimal Places Accurately for a NumberExample 3: Create a Program that divides two numbers and returns their decimal placesExample 4: Find the Number of […]

  • 02 November

    Check if String Is Empty in C++

    Table of ContentsWays to Check if String Is Empty in C++Using Empty() methodUsing the Equality OperatorUsing length() methodUsing size() methodConclusion A String is a combination of characters that can store both alphabets and numbers together. In C, there was no concept of string as a datatype so character arrays were used. In C++, this drawback […]

  • 03 October

    Get Filename from Path in C++

    Table of ContentsGet Filename From Path in C++Using find_last_of and substr methodsUsing TemplatesUsing filesysystem library [ C++ 17 ]Conclusion This article explains the various ways to get filename from path using C++ programs. The examples will also describe ways to remove extensions as well if such needs arise. Get Filename From Path in C++ Finding […]

  • 24 September

    Escape Percent Sign in printf Method in C++

    In this post, we will see how to escape percent sign in printf Method in C++. Escape percent sign in Printf Method in C++ printf() method uses percent sign(%) as prefix of format specifier. For example: To use number in prinf() method, we use %d, but what if you actually want to use percent sign […]

  • 15 September

    Remove Last Element from Vector in C++

    Table of ContentsWays to Remove Last Element from Vector in C++Using the vector::pop_back() function to remove last element from vector in C++Using the vector::resize() Function to Remove Last Element from Vector in C++Using the vector::rrase() Function to Remove Last Element from Vector in C++Conclusion Learn about how to remove last element from Vector in C++. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.