File Handling in C++
File Handling in C++
What is File Handling?
In today's era, data plays an important role. It is used by almost every financial institution to control its operations efficiently. But to retrieve data, we need to store it somewhere. You would argue that there are numerous text editors like ‘Notepad’ and ‘MS Office’, which allow us to store data within the form of text. That's right! But in this case, we need to resolve this from the perspective of a programmer. In contrast, text editors like ‘Notepad’ and ‘MS Office’ are pre-built and can't be accessed at the programming level to store data. File handling provides a mechanism to store the output of a program during a file and to perform various operations thereon. Files are used to store data permanently.
This topic is divided into the following sub-topics:
- Create a file
- Open a file
- Read from a file
- Write to a file
- Close a file
Getting Started with File Handling
In C++, files are mainly operated by using three classes fstream, ifstream, ofstream.
- ofstream: This Stream class represents the output stream and is used to create files for writing information to files
- ifstream: This Stream class represents the input stream and is used for reading information from files
- fstream: This Stream class is often used for both read and write from/to files.
All the aforementioned classes are derived from the fstreambase and the corresponding iostream classes.
To access these classes, you must include the fstream as a header file like how we declare iostream in the header as shown:
1 2 3 | #include<iostream> #include<fstream> |
- open() – This is used to create a new file or open an existing one.
- read() – This is used for reading data from the file.
- write() – This is used for writing new data to the file.
- close() – This is used for closing the file.
Opening a file in C++
To read or enter data to a file, we would want to open it first. This can be performed with the aid of ‘ifstream’ for reading and ‘fstream’ or ‘ofstream’ for writing or appending to the file. The objects of these classes have open() function pre-built in them.
Syntax:
1 | open(FileName, Mode); |
FileName – It indicates the name of file that is to be opened.
Mode – There are different modes to open a file as follows:.
Mode | Description |
iso::in | File opened in reading mode |
iso::out | File opened in write mode |
iso::app | File opened in append mode |
iso::ate | File opened in append mode but read and write performed at the end of the file. |
iso::binary | File opened in binary mode |
iso::trunc | If the file already exists, its contents will be truncated before opening the file |
In C++, we can use two modes simultaneously with the help of | (OR) operator.
Closing a file in C++
On termination of a C++ program, the compiler automatically releases allocated memory and closes all the opened files. But it is always a good practice for a programmer to close all the opened files before program termination.
Syntax:
1 | FileName.close(); |
Program for Opening a File in write mode and Closing the file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include<iostream> #include<fstream> using namespace std; int main(){ fstream FileName; FileName.open( "NewFile.dat" , ios::out | ios::binary); if (!FileName){ cout<< "Error while creating the file" ; } else { cout<< "File created successfully" ; FileName.close(); } return 0; } |
Output
File created successfully
Writing to a File
Till now, we learned how to create a file using C++. Now, we will learn how to write data to the file we created. We will use fstream or ofstream object to write data into the file and to do so, we will use stream insertion operator (<<) along with text enclosed within double-quotes.
Syntax:
1 | FileName<< "Insert the text here" ; |
Program for Writing to File:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> #include<fstream> using namespace std; int main() { fstream FileName; FileName.open( "File.txt" , ios::out); if (!FileName) { cout<< "Error while creating the file " ; } else { FileName<< "I am a text file. I can be read or written." ; FileName.close(); cout<< "File created and data written to file" ; } return 0; } |
Console Output
File created and data written to file
Content of File.txt
I am a text file. I can be read or written.
Reading from a file
Retrieving data from a file is very crucial in order to operate on it. For reading a file, you use either the fstream or ifstream object. In case you want to read the file line by line, and to print the content of the file, use a while loop along with the getline () function. You could also read the file contents character by character using a while loop and eof () method.
To read information from a file, you need to use the stream extraction operator (>>).
Syntax:
1 | FileName>>Variable; |
Content of File.txt:
I am a text file. I can be read or written.
Program for Reading from File:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include<iostream> #include <fstream> using namespace std; int main() { fstream FileName; FileName.open( "File.txt" , ios::in); if (!FileName) { cout<< "File doesn’t exist." ; } else { char x; while (1) { FileName>>x; if (FileName.eof()) break ; cout<<x; } } FileName.close(); return 0; } |
Console Output
I am a text file. I can be read or written.
Program to read the file line by line
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | int main() { fstream FileName; FileName.open( "File.txt" , ios::in); if (!FileName) { cout<< "File doesn’t exist." ; } else { string line; while (getline(FileName, line) { cout<<line<<endl; } } FileName.close(); return 0; } |
File Pointers and Manipulation
Every file contains two pointers: a read pointer, also referred to as a get pointer and a write pointer, also referred to as a put pointer. The get pointer is employed to read data whereas the put pointer is employed to write data to a file. These pointers are often manipulated using the functions from stream classes. Those functions are as follows:
seekg() is used to move the get pointer to a desired location with respect to a reference point.
Syntax: file_pointer.seekg (number of bytes, Reference point);
Example: fin.seekg(10, ios::beg);
tellg() is used to know where the get pointer is in a file.
Syntax: file_pointer.tellg();
Example: int posn = fin.tellg();
seekp() is used to move the put pointer to a desired location with respect to a reference point.
Syntax: file_pointer.seekp(number of bytes, Reference point);
Example: fout.seekp(10, ios::beg);
tellp() is used to know where the put pointer is in a file.
Syntax: file_pointer.tellp();
Example: int posn=fout.tellp();
The reference points are:
ios::beg – from beginning of file
ios::end – from end of file
ios::cur – from current position in the file.
In seekg() and seekp(), if you put a '–' sign in front of number of bytes, you could move backwards.
Types of Files
C++ supports two types of files. They are text files and binary files.
Text Files
A text file is a sequence of characters which is processed sequentially by a computer. As they only process characters, text files read or write data one character at a time. In a text file, each line contains zero or more characters and ends with one or more characters that specify the end of a line.
In a text file, data of all types is stored as a sequence of characters and each file ends with a special character referred to as end of file marker.
Binary Files
A binary file contains data converted to binary format for computer storage and processing. A binary file is non-human readable. A binary file does not require any special processing of the data and each byte of data is transferred from the disk unprocessed. While text files can be processed sequentially, binary files can be processed sequentially or in a random fashion.
Binary files store data in internal representation format i.e., if we store an integer 42, it only occupies a single byte. Whereas in text file, it occupies two bytes. One byte to store character 4 and another byte to store character 2.
|
Wow!
ReplyDeleteVery informative !
ReplyDeleteInformative article. Definitely worth the read.
ReplyDeleteAwesome blog
ReplyDeleteVery useful. Thank you for such a good blog.
ReplyDeleteSuch a systematic blog, proper use of example, syntax and step wise code. Each and every point is explained so well. Great workπ
ReplyDeleteVery well written blog!!ππ»
ReplyDeletereally informative π
ReplyDeleteInformative !
ReplyDeleteConcise π
ReplyDeletevery well written blog with very useful information for a programmer learning about file handling.
ReplyDeleteConcise and quality content!!
ReplyDeleteVery goodππ»ππ»
ReplyDelete