WHAT IS FILE HANDLING?
- In C++, file handling is done using file streams where file means it is used to store the information or data and streams refer to sequence of bytes.
- In files we store data i.e. text or binary data permanently and use these data to read and write in the form of input and output operations by transferring the bytes of data.
- So, till now we were using iostream standard library, which provides cin for reading from the provided input and cout for writing to the standard output.
In C++, the files are handled by using three classes’ ifstream, ofstream and fstream and the header file fstream is used.
LET US DISCUSS THESE THREE STREAMS:
- ifstream: It type represents the input file stream and it is used to read the data from the files.
- ofstream: It represents the output file stream and is used to create files and to write data to files.
- fstream: It represents the file stream and has the features of both the streams ifstream and ofstream which means it can create files, write the information to file and read the information from files.
Operations in File Handling
LET US HAVE A LOOK AT THE OPERATIONS IN FILE HANDLING:
Creating or Opening a file
We can create or open a file by giving a specific path of the file and mode of operation. The operations than can be performed are reading, writing, appending and truncating.
SYNTAX FOR CREATING A FILE IS:
There are some different modes in which we can open a file:
- ios::app – It opens a text file for appending which means we can add the text at the end.
- ios::in – It opens a text file for reading.
- ios::out – It opens a text file for writing.
- ios::trunc – It truncates the content before opening a file, if file exists.
- ios::ate – It opens a file for output and move the read/write control to the end of the file.