File Handling: Course Code: CSC1102 &1103 Course Title: Introduction To Programming
File Handling: Course Code: CSC1102 &1103 Course Title: Introduction To Programming
File Handling: Course Code: CSC1102 &1103 Course Title: Introduction To Programming
Files are used to store data in a storage device permanently. When a program runs,
the data is in the memory but when it ends or the computer shuts down, it gets lost.
To keep data permanently, we need to write it in a file.
File handling provides a mechanism to store the output of a program in a file and to
perform various operations on it.
Many real-life scenarios are there that handle a large number of data, and in such
situations, you need to use some secondary storage to store the data. The data are
stored in the secondary device using the concept of files.
Streams
In C++ programming we are using the iostream standard library, it provides cin and
cout methods for reading from input and writing to output respectively.
To read and write from a file we are using the standard C++ library called fstream.
Let us see the data types define in fstream library is:
fstream A combination of ofstream and ifstream: creates, reads, and writes to files
Operations in File Handling
A file must be opened before you can read from it or write to it. Either
ofstream or fstream object may be used to open a file for writing. And
ifstream object is used to open a file for reading purpose only.
There are some mode flags used for file opening. These are:
Mode Description
ios::in Opens the file to read(default for ifstream)
Output
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream file;
file.open ("example.txt");
return 0;
}
Closing A FILE
When a C++ program terminates it automatically flushes all the streams, release
all the allocated memory and close all the opened files. But it is always a good
practice that a programmer should close all the opened files before program
termination.
void close();
int main(){
ofstream file;
file.open ("example.txt");
file.close();
return 0;
}
Write to A FILE
int main(){
// Create and open a text file
ofstream MyFile("example.txt");
Note that we also use a while loop together with the getline() function
(which belongs to the ifstream object) to read the file line by line, and
to print the content of the file.
Read from A FILE [ example ]
#include <iostream>
#include <fstream>
using namespace std;
Output
int main(){
string line;
ifstream file("example.txt");