Program to read and write to a file in C++
Written by
# 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;
ob.open("test.txt", ios::out); // opening file in writing mode
ob << "hello world\n"; // writing data to file
ob << "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 >> str; // reading word by word from file and storing in str
cout << str << "\n"; // printing str
}
ob.close(); // closing the file after use
return 0;
}
Output