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.

Conclusion

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

  • 19 May

    Get Type of Object in C++

    Table of ContentsWhy Should We Determine the Type of Object in C++: Dynamic DispatchingGet Type of Object in C++ConclusionWas this post helpful? C++ is an object-oriented language where we often interact with objects of different types. The object interaction becomes more interesting when we add runtime polymorphism to it. The runtime polymorphism, also known as, […]

  • 19 May

    Convert Vector to Array in C++

    Table of ContentsVectors and Arrays in C++Convert Vector to Arrays in C++Using the for loop to convert vector to array in C++Using the copy() function to convert vector to array in C++Using the transform() function to convert vector to array in C++Using the data() function to convert vector to array in C++Using the & operator […]

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusionWas this post helpful? This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusionWas this post helpful? An […]

  • Print Vector C++
    23 March

    Print Vector in C++

    Table of ContentsPrint Vector in C++ Using IndicesPrint Vector in C++ Using Range-Based for LoopPrint Vector in C++ Using for_each() FunctionPrint Vector in C++ Using IteratorPrint Vector in C++ by Overloading the Insertion Operator (<<)Print Vector in C++ Using copy() FunctionConclusionWas this post helpful? This article discusses the vector and how to print vector in […]

  • Print Map in C++
    15 March

    Print Map in C++

    Table of ContentsMap vs Unordered MapPrint Map in C++ Using IteratorPrint Map in C++ Using Range-Based for LoopPrint Map in C++ by Overloading the ostream Insertion Operator (<<)Print Map in C++17 Using Structure Binding and Range-Based for LoopPrint Map in C++17 Using for_each() FunctionConclusionReferencesWas this post helpful? Maps in C++ store the data in form […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.