Skip to content
Saturday, November 28, 2026Ideas worth exploring. Knowledge worth sharing.
S. SenseCentralDISCOVER EVERY DAY
C++ Programming

C++ Files and Streams

The iostream standard library cin and cout methods for reading from standard input and writing to standard output respectively.

To read and write from a file requires another standard C++ library called fstream which defines three new data types:

Data TypeDescription
ofstreamThis data type represents the output file stream and is used to create files and to write information to files.
ifstreamThis data type represents the input file stream and is used to read information from files.
fstreamThis data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

Following is the C++ program, which opens a file in reading and writing mode. After writing information inputted by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen:

#include<fstream>

#include<iostream>

usingnamespacestd;

int main ()

{

char data[100];

// open a file in write mode.

ofstreamoutfile;

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.

ifstreaminfile;

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();

return0;

}

Author

  • A senior editor for The Mars that left the company to join the team of SenseCentral as a news editor and content creator. An artist by nature who enjoys video games, guitars, action figures, cooking, painting, drawing and good music.

WRITTEN BY

Taylor Emma

A senior editor for The Mars that left the company to join the team of SenseCentral as a news editor and content creator. An artist by nature who enjoys video games, guitars, action figures, cooking, painting, drawing and good music.

More from this author ↗

Leave a Reply

Your email address will not be published. Required fields are marked *