[go: up one dir, main page]

0% found this document useful (0 votes)
11 views3 pages

Read and Write Example

The document provides a C++ program that demonstrates how to open a file for reading and writing. It allows the user to input their name and age, which are then written to a file named 'afile.dat'. After writing, the program reads the data back from the file and displays it on the screen.

Uploaded by

Shub P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Read and Write Example

The document provides a C++ program that demonstrates how to open a file for reading and writing. It allows the user to input their name and age, which are then written to a file named 'afile.dat'. After writing, the program reads the data back from the file and displays it on the screen.

Uploaded by

Shub P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Read and Write Example

Following is the C++ program which opens a file in reading and writing mode. After writing information entered
by the user to a file , the program reads information from the file and outputs it onto the screen
−#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;
•}

You might also like