Text File Handling in C++
File Handling in C++
In this lesson, we will learn how to handle text file in C++.
What is Text File Handling
Text File Handling is a process in which we create a text file and store data permanently on a hard disk so that it can be retrieved from the memory later for use in a program.
In a text file, whatever data we store is treated as text. Even if we store numbers, it is treated as text.
Types of Stream Classes Use for File Handling
A stream is a sequence of bytes. Streams are used to perform input and output operations in C++, such as reading from a file or writing to a file. There are mainly three types of stream classes used in C++ to handle files, and they are:
- ofstream
- ifstream
- fstream
ofstream
The ofstream is a type of output stream in C++ that is used to write data to a file. We must include the fstream header file in our program to use the ofstream class.
Syntax
ofstream object_name;
object_name.open("file_name");
ifstream
The ifstream is a type of input stream in C++ that is used to read data from a file. We must include the fstream header file in our program to use the ifstream class.
Syntax
ifstream object_name;
object_name.open("file_name");
fstream
The fstream is a type of file stream in C++ that is used for reading from, writing to, and manipulating files. We must include the fstream header file in our program to use the fstream class.
Syntax
fstream object_name;
object_name.open("file_name", mode);
Below we have discussed the different types of file opening modes use to open a text file using the fstream class object.
Mode | Description |
ios::in | This mode is used to open a file for reading. The file pointer is placed at the beginning of the file. It is the default mode when a file is opened without any specified mode. |
ios::out | This mode is used to open a file for writing. If the file does not exist, it will be created. If the file already exists, it will be overwritten. The file pointer is placed at the beginning of the file |
ios::app | This mode is used to open a file for appending. If the file does not exist, it will be created. If the file already exists, all new data will be added to the end of the file. |
ios::in | ios::out | This mode is used to open a file for both reading and writing. The file pointer is placed at the beginning of the file. |
ios::in | ios::out | ios::trunc | This mode is used to open a file for both reading and writing, and truncates the file to zero length if it already exists. The file pointer is placed at the beginning of the file. |
ios::in | ios::out | ios::app | This mode is used to open a file for both reading and writing, and all new data will be added to the end of the file. |
ios::in | ios::out | ios::ate | This mode is used to open a file for both reading and writing, and the file pointer is placed at the end of the file. |
Operation on Text File
There are different types of operations that we can perform on a text file, they are:
- Create a new file.
- Open an existing file.
- Write to a file.
- Read from a file.
- Copy a file from one location to another.
- Rename a file.
- Delete a file.
Create a new file
The program given below demonstrates how we can create a new text file in memory.
Example
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("e:/data.txt", ios::out);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
fs.close();
return 0;
}
In the above program, we created fstream object fs and used the open() method to open a file using the ios::out mode. After that, we used the is_open() method to check if the file opened successfully or not. This method returns 1 if the file is opened; otherwise, it returns 0 when it cannot open the file.
The close() method is used to close the file which is opened in the memory.
Open an existing file
The program given below demonstrates how we can open an existing text file.
Example
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("e:/data.txt", ios::in);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
fs.close();
return 0;
}
In the above program, we have opened the file data.txt for reading using the read mode ios::in.
Write to a file
The program given below demonstrates how we can write some text in a text file.
Example
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{
fstream fs;
char str[200];
fs.open("e:/data.txt", ios::app);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
else
{
cout<<"Enter a few lines of text:\n";
while(strlen(gets(str)) > 0)
{
fs<<str<<endl;
}
fs.close();
}
return 0;
}
In the above program, we have used a character array str of size 200 to store whatever we write on the screen using gets() function.
With help of while loop we are checking if the length of the str is greater than 0 then write all the contents of str into the file using the << insertion operator. After that we write a new line character into the file to break the line using the endl statement.
The while loop stops working when we press the enter key from the keyboard twice without writing anything on the screen. In this case the length of str becomes 0 and the loop terminates.
We close the file using close() method after the while loop terminates.
Read from a file
We can read the content of a file in two different ways. Lets's see both ways of reading the file using the examples given below.
Example 1
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
char c;
fs.open("e:/data.txt", ios::in);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
else
{
while(!fs.eof())
{
fs.get(c);
cout<<c;
}
fs.close();
}
return 0;
}
In the above program, we have run an infinite while loop to read all the characters from the file until we get the end of file character using eof() method. We read individual characters from the file in a character variable c using the get() method and print it on the screen. The while loop terminates when we get the eof character from the file.
Example 2
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
string line;
fs.open("e:/data.txt", ios::in);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
else
{
while(getline(fs,line))
{
cout<<line<<endl;
}
fs.close();
}
return 0;
}
In the above program, we have used a while loop that uses the getline() function to read a line from the file in a string variable line. We print the line along with the new line character using the endl statement on the screen. The while loop terminates when the getline() function reaches the end of the file.
Copy a file from one location to another
The program given below demonstrates how to copy a file from one location to another.
Example
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs1, fs2;
string line;
fs1.open("e:/data.txt", ios::in);
fs2.open("e:/data2.txt", ios::out);
if(fs1.is_open()==0)
{
cout<<"Cannot open source file";
}
else
{
while(getline(fs1,line))
{
fs2<<line<<endl;
}
cout<<"File copied successfully";
}
fs1.close();
fs2.close();
return 0;
}
In the above program, we have opened two files in two different modes, fs1 is the source file object opened in read mode, and fs2 is the destination file object opened in write mode. With the help of a while loop, we read a line from the source file and write it into the destination file using the fs2 object. When the loop terminates, we close both files using the close() method.
Rename a file
The program given below demonstrates how to rename a file.
Example
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
rename("E:/data.txt", "E:/data2.txt");
printf("File renamed successfully");
return 0;
}
Note: Before renaming the file, make sure that the file is closed else it cannot be renamed.
Delete a file
The program given below demonstrates how to delete a file.
Example
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
remove("E:/data2.txt");
printf("File Deleted Successfully");
return 0;
}
Note: Before deleting the file, make sure that the file is closed else it cannot be deleted.
File Pointer Movements
We can move file pointer associated with a file to a specific position in the file using the functions given below.
- seekg()
- seekp()
- tellg()
- tellp()
seekg()
The seekg() function moves the get pointer of the ofstream to a specific position in a file from where we want to read the file.
Syntax
stream_object.seekg(number_of_bytes, from_position);
- number_of_bytes: It specifies the number of bytes the file pointer should move forward in the file. Negative value moves the file pointer backward.
- from_position: It specifies the position in the file from where the file pointer should move forward or backward.
There are three types of from_position and they are:
- ios::beg: It moves the file pointer to the specified number of bytes from the beginning of the file.
- ios::cur: It moves the file pointer to the specified number of bytes from the its current position in the file.
- ios::end: It moves the file pointer to the specified number of bytes from the end of the file.
tellg()
The tellg() function gives the current position of the get pointer in the file.
Syntax
stream_object.tellg();
seekp()
The seekp() function moves the file put pointer of the ifstream to a specific position in a file from where we want to write in the file.
Syntax
stream_object.seekp(number_of_bytes, from_position);
tellp()
The tellp() function gives the current position of the put pointer in the file.
Syntax
stream_object.tellp();
Example of File Pointer Movements
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
char s[]="I am learning C++ Programming from dremendo.com";
char c;
int i;
fs.open("e:/data.txt", ios::in | ios::out);
if(fs.is_open()==0)
{
cout<<"Cannot open file";
}
else
{
// writing some text in the file
fs<<s;
// move the file pointer from the beginning of the file to 5th character for reading
fs.seekg(5, ios::beg);
// read 12 characters from the current position
for(i=1; i<=12; i++)
{
fs.get(c);
cout<<c;
}
// move the file pointer 11 charaters backward from its current position
fs.seekg(-11, ios::cur);
// read 3 characters from the current position
cout<<endl;
for(i=1; i<=3; i++)
{
fs.get(c);
cout<<c;
}
// move the file pointer from the beginning of the file to 17th character for writing
fs.seekp(17, ios::beg);
// write and Java from the current position
fs<<" and Java";
// move the file pointer to the beginning of the file for reading
fs.seekg(0, ios::beg);
// read the entire file from the beginning
cout<<endl;
while(!fs.eof())
{
fs.get(c);
cout<<c;
}
}
fs.close();
return 0;
}
Output
learning C++ arn I am learning C++ and Javaing from dremendo.com