Before understanding the concepts of data file handling, let’s first understand what a stream is.
Simply put, a stream is a sequence of bytes.
It is a general name given to the flow of data at the very naïve level.
There are different kinds of streams used that represents different kind of flow of data.
When data flows from outside of the program to inside of a disk file then it is called output stream.
On the other hand, when data flows from the outside of a disk file to the inside of the program then it is called input stream.
All the these streams are handled by the header file fstream.h
Note: All the classes of fstream.h inherit from the classes inside iostream.h, so when we include fstream.h we do not need to include iostream.h
Why do we need data file?
In our program we use variables to store the data, but that data is not accessible after the execution of program finishes.
This is because all the variables are destroyed after our program completes its execution.
So if we want to store our data permanently and for later use we have to store them inside data files and put those data files on hard disk so that they are stored permanently.
Types of data file
There are mainly two types of data files used
- Text data file: It stores data in the form of ASCII characters and there is an EOL (end of line) character at the end.
- Binary file: It stores the information in the form of bits (0 and 1) and there is no EOL character at the end. It is the actual way in which data is stored inside a computer memory. These files are much faster to read or write compared to text files.
Opening and closing data files
To understand how to handle data files first we have to understand how to open and close them.
Opening a data file: We can open data files in two ways -->
stream-type stream-object (“filename”) ;
Here we opened a file using a stream-object of a particular stream-type and provided the name of the file to be opened to it.
Stream types can be ifstream, ofstream and fstream. We’ll look at these stream types shortly.
ifstream iff (“myfile.txt”);
We created an ifstream object iff and passed the file to be opened myfile.txt
stream-object.open(“filename”);``` This is the second way to open a file. First a stream object is created and the file is opened using the open() function of that object. For example: ```ifstream iff; iff.open(“myfile.txt”);``` Closing data file: Files are simply closed using the syntax, ```stream-object.close()```
Note: This statement only closes the file attached to the stream, the stream is still available to be connected to another file.