TutorialStudyMite
Program to read and write to a file in C++
GGarvit Gulati1 min read
Beginner friendly
Track completion, mastery, and revision.
# 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
- To process a file in C++, we can use the functions provided in the
<fstream>header file. This includes functions for opening, reading, and writing to text files. - Follow these steps to process a file:
- Open the file: Use the
open()function and specify the mode (e.g.ios::in,ios::out) to tell the compiler whether to read from or write to the file. - Work on the file: Use the appropriate functions to read and write to the file as needed.
- Close the file: After you have finished working with the file, be sure to close it before terminating the program.
- Open the file: Use the
- To write to a file, you can use the cascade operator (
<<) or theput()function to write character by character. - To read from a file, you can use the cascade operator (
>>) to read word by word, or use thegetline()function to read line by line and thegetchar()function to read character by character. - Note that the
<fstream>header file is a superset of<iostream>, so you don't need to include<iostream>separately.
Code
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream ob;
// Open in write mode
ob.open("test.txt", ios::out);
ob << "hello world\n";
ob << "this is my first file";
ob.close();
// Open in read mode
ob.open("test.txt", ios::in);
string str;
while (ob >> str) {
cout << str << "\n";
}
ob.close();
return 0;
}
Output

Finished reading?