File handling in C++
File handling
Common operations on files are open,read , write and close. Below mentioned code snippet
exhibits these operations;
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("umar.txt");
cout << "\nWriting to the file\n";
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "\n Enter your RollNumber: ";
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("umar.txt");
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();
system("pause");
return 0;
}
By hafiz Muhammad Umar Hayat
Comments
Post a Comment