# Program to read and write to a file in C++

Written by

Garvit Gulati

### # Understanding the question

In this program, we have to create a file, write something to that file, and then extract that data from that file and print it on our screen.

### # Approaching the question

1. C++ provides functions to open, read and write to text files in the header file <fstream>. We have to declare on object of type fstream in order to use the functions provided.
2. Steps to process a file:
1. Opening the file:This is done with the help of open() function. We have to specify the mode(in,out etc) in   order to tell the compiler wether to read from or write from the file.
2. Working on the file:After opening a file, we use functions to read and write to the file as per our requirements.
3. Closing the file:After our work is finished, we need to close the file before terminating the program.
3. To write to a file, we will use cascade operator(<<). Alternatively, one can use put() function to write character by character to a file.
4. To read from a file, we will follow the cascade operator(>>) approach. Cascade operator reads word by word from file i.e. From space to space. Alternatively, one can use getline() to read line by line from a file and getchar() to read character by character from a file.
5. NOTE: fstream header file is a super set of iostream, hence, we don’t need to include iostream.

Code

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream ob;
ob.open("test.txt", ios::out);	//opening file in writing mode

ob &lt;&lt; "hello world\n";	//writing data to file

ob &lt;&lt; "this is my first file";

ob.close();	//closing the file

ob.open("test.txt", ios:: in);	//again opening the file but in reading mode

while (!ob.eof())

{
string str;

ob &gt;&gt; str;	//reading word by word from file and storing in str

cout &lt;&lt; str &lt;&lt; "\n";	//printing str

}

ob.close();	//closing the file after use

return 0;

}

Output