Table of Contents
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.
1 2 3 4 |
void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include<iostream> #include<fstream> using namespace std; int main() { fstream file; file.open("sample_file.txt", ios_base::out); if(!file.is_open()) { cout<<"Unable to open the file.\n"; return 0; } string myStr = "Hi! We are Java2Blog. Follow us for learning more!"; file<<myStr; file.close(); return 0; } |
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):
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.
1 2 3 |
ostream& write (const char* s, streamsize n); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include<iostream> #include<fstream> using namespace std; int main() { fstream file; file.open("sample_file_2.txt", ios_base::out); if(!file.is_open()) { cout<<"Unable to open the file.\n"; return 0; } string myStr = "Hi! We are Java2Blog. This is example of write method!"; file.write(myStr.data(), myStr.size()); file.close(); return 0; } |
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):
Further reading:
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.
1 2 3 |
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include<iostream> using namespace std; int main() { string myStr = "Hi! We are Java2Blog. This is example of fwrite function."; FILE * file = fopen("sample_file_3.txt", "w+"); if(file) { fwrite(myStr.data(), sizeof(char), myStr.size(), file); } else { cout<<"Unable to open the file\n"; return 0; } return 0; } |
Output (from the file):
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!