| Datatype | Description |
|---|
| ofstream | Used for creating a file and write data on files. |
| ifstream | Used for reading the data from files. |
| fstream | Used for both read and write data from files. |
| Function | Description |
|---|
| open() | It is used to create a file. |
| close() | It is used to close an existing file. |
| get() | It is used to read a single unit character from a file. |
| put() | It is used to write a single unit character in file. |
| read() | It is used to read data from file. |
| write() | It is used to write data into file. |
1. Naming a file
2. Opening a file
3. Reading data from file
4. Writing data into file
5. Closing a file
| File mode | Description |
|---|
| ios::out | This mode is opened for writing a file. |
| ios::in | This mode is opened for reading a file. |
| ios::app | This mode is opened for appending data to end-of-file. |
| ios::binary | The file is opened in binary mode. |
| ios::ate | This file moves the pointer or cursor to the end of the file when it is opened. |
| ios::trunc | If the file is already exists, using this mode the file contents will be truncated before opening the file. |
| ios::nocreate | This mode will cause to fail the open() function if the file does not exists. |
| ios::noreplace | This mode will cause to fail the open function if the file is already exists. |
All these above modes can be combined using the bitwise operator (|). for example, ios::out | ios::app | ios::binary
| Function | Description |
|---|
| put() | This function writes a single character to the associated stream. |
| get() | This function reads a single character to the associated stream. |
| write() | This function is used to write the binary data. |
| read() | This function is used to read the binary data. |
| Function | Description |
|---|
| seekg() | It moves the get pointer (input) to a specified location. |
| seekp() | It moves the put pointer (output) to a specified location. |
| tellg() | It gives the current position of the get pointer. |
| tellp() | It gives the current position of the put pointer. |
Example: Program demonstrating Read and Write mode of a file
Following program reads the information from the file and displays it onto the screen.
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char name[50];
ofstream ofile; // open a file in write mode.
ofile.open("abc.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: "<<endl;
cin.getline(name, 50);
cout<<endl;
ofile << name << endl; // write inputted data into the file.
ofile.close(); // close the opened file.
ifstream ifile; // open a file in read mode.
ifile.open("abc.dat");
cout << "Reading from the file" << endl;
ifile >> name;
cout << name << endl; // write the data at the screen.
ifile.close(); // close the opened file.
return 0;
}