File in C++ is used to read write append data. For doing it we use the classes meant for File handling.
Data Type |
Description |
ofstream |
This data type represents the output file stream and is used to create files and to write information to files. |
ifstream |
This data type represents the input file stream and is used to read information from files. |
fstream |
Normally the file streams are represented by fstream data type and it has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files. |
Opening a File:
Opening a file means that a file first needs to opened before performing any manipulation. To open a file for writing either ofstream or fstream object has to be used to open a file and to open a file for only for reading ifstream object is used.
Here is the example for ofstream
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Here is the example for fstream
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program is terminated it deallocate all the memory and close all the opened files.
We use predefined function for it.
void close();
Writing to a File:
ofstream or fstream are the classes that will be used for writing a file.
Reading to a File:
ifstream or fstream are the classes that will be used for reading a file.
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
0 Comment(s)