C++ Files

Files are an essential part of the computer system and it plays a significant role in the storage and retrieval of data. C++ provides various functions to perform various file operations, such as creating, reading, and writing to a file. In this article, we will learn about the creation and writing to a file and reading a file in C++.

Create and Write To a File

The first step to perform file operations is to open a file. C++ provides two functions to open a file: "ofstream" and "fstream". The "ofstream" function is used to create and write to a file, while the "fstream" function is used to open a file in both reading and writing mode.

Let's take an example to create a file and write data to it:

1#include<iostream> 2#include<fstream> 3using namespace std; 4 5int main() 6{ 7 ofstream file; 8 file.open("example.txt"); 9 file << "Hello World!!" << endl; 10 file.close(); 11 cout << "Data written to the file successfully!!" << endl; 12 return 0; 13}

Output: Data written to the file successfully!!

In the above example, we have created a file named "example.txt" using the "ofstream" function. We have used the "open" function to open the file, and the "<<" operator to write data to the file. Finally, the "close" function is used to close the file.

Read a File

The next step is to read the data from the file. C++ provides two functions to read a file, "ifstream" and "fstream". The "ifstream" function is used to read a file, while the "fstream" function is used to open a file in both reading and writing mode.

Let's take an example to read the data from a file:

1#include<iostream> 2#include<fstream> 3#include<string> 4using namespace std; 5 6int main() 7{ 8 string data; 9 ifstream file; 10 file.open("example.txt"); 11 while(file) 12 { 13 getline(file, data); 14 cout << data << endl; 15 } 16 file.close(); 17 return 0; 18}

Output: Hello World!!

In the above example, we have used the "ifstream" function to read the data from the file. The "open" function is used to open the file, and the "getline" function is used to read the data from the file. The "while" loop is used to read the data from the file until the end of the file is reached. Finally, the "close" function is used to close the file.