C++ File Handling
A file in C++ is a named location which is used to store data in a non-volatile memory (e.g. hard disk). The main memory (i.e. RAM) is volatile in nature and loses its data when computer is turned off. That’s why files are needed for future use of the data.
When we want to write to or read from a file we need to open it first. And when our work is completed, it needs to be closed, so that resources that are associated with the file are released.
In C++, the file operation may take place in the following sequence:
- Open a file
- Perform write or read or append operation
- Close the file
Let us discuss about fopen() and fclose() functions in C++. We will use these functions to write some programs to demonstrate various file operations.
After that, we will describe the use of different file streams in C++.
C++ fopen() function
We use the fopen() function in C++ to open a specified file in a certain mode. It is defined in header file.
Basically, fopen() function takes two arguments and returns a file stream associated with that file specified by the argument filename.
Prototype of function fopen():
FILE* fopen (const char* filename, const char* mode);
fopen() Parameters:
- filename: pointer to the string containing the name of the file to be opened.
- mode: pointer to the string that specifies the mode in which file is opened.
fopen() return value:
- On success, the
fopen()
returns a pointer to the FILE object that controls the opened file stream. - On failure, it returns a null pointer.
There are several types of mode, that C++ provides and how files can be opened:
- “r“, to open a file for reading (read from the start)
- “w“, to open a file for writing (erase all the contents)
- “a“, to open a file for appending (start writing from the end)
- “r+“, to open a file for both reading and writing (read from the start)
- “w+“, to open a file for both reading and writing (erase all the contents)
- “a+“, to open a file for both reading and writing (start writing from the end)
C++ fclose() function
The fclose() function in C++ closes the given file stream. It is defined in header file.
Prototype of function fclose():
int fclose(FILE* stream);
The fclose()
function takes a single argument, a file stream which is to be closed.
Example 1. Opening a file in write mode
To write to a file, we have to use the parameter “w” to the fopen()
function apart from the file name itself. Let us look at a program to write to a file named “sample.txt” (create a new file if it does not exist). We will use the putc() function here. See the code below:
// to create a file for writing
#include <cstdio>
#include <cstring>
using namespace std;
int main() {
int c;
FILE *fp;
fp = fopen("sample.txt", "w");
char str[50] = "Welcome to sample.txt file. Happy learning!";
if (fp) {
for(int i=0; i<strlen(str); i++)
putc(str[i], fp);
}
fclose(fp);
return 0;
}
When we run the program, it will not generate any output but will write “Welcome to sample.txt file. Happy learning!” to the file “sample.txt“.
Example 2. Opening a file in read mode
To read from a file, we have to use the parameter “r” to the fopen()
function apart from the file name itself. Let us look at the simple program to open a file named “sample.txt” (stored in the same directory) and printing its content on the console using the putchar() method:
// Opens a text file in read mode
#include <cstdio>
using namespace std;
int main() {
int c;
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp) {
while ((c = getc(fp)) != EOF)
putchar(c);
}
fclose(fp);
return 0;
}
Output:
Welcome to sample.txt file. Happy learning!
Example 3. Opening a file in append mode
To append to a file, we have to use the parameter “a” to the fopen()
function apart from the file name itself. Let us look at a program to append to a file named “sample.txt”. We will use the putc() function here. See the code below:
// code to append to a file
#include <cstdio>
#include <cstring>
using namespace std;
int main() {
int c;
FILE *fp;
fp = fopen("sample.txt", "a");
char str[30] = "It is for test purposes only.";
if (fp) {
putc('\n', fp);
for(int i=0; i<strlen(str); i++)
putc(str[i], fp);
}
fclose(fp);
return 0;
}
When we run the program, it will not generate any output but will append “It is for test purposes only.” in a newline to the file “sample.txt“.
C++ File Streams
In C++ programming we basically using the iostream standard library, it provides cin and cout objects for reading from input and writing to output respectively.
fstream is another C++ standard library like iostream and is used to read and write on files.
The following are the data types used for file handling from the fstream library:
Data type | Description |
---|---|
ofstream | It is used to create files and write on files. |
ifstream | It is used to read from files. |
fstream | It can perform the function of both ofstream and ifstream which means it can create files, write on files, and read from files. |
NOTE: To perform file processing in C++ using the fstream library, header files and must be included in the source program.
Opening a file using fstream
We need to tell the computer the purpose of opening our file. For example – to write to a file, to read from a file etc.
Let us look at the syntax of opening a file, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument (optional argument) of the open() member function defines the mode in which the file should be opened (see the table below).
These are the different modes in which we can open a file.
Mode | Description |
---|---|
ios::app | opens a text file for appending (appending means to add text at the end). |
ios::ate | opens a file for output and move the read/write control to the end of the file. |
ios::in | opens a text file for reading. |
ios::out | opens a text file for writing. |
ios::trunc | truncates the content before opening a file, if file exists. |
Closing a file using fstream
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Example 4. Write to a file
To create a file, use either the ofstream
or fstream
class, and specify the name of the file.
To write to the file, we need to use the insertion operator (<<
).
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// create and open a text file
ofstream file;
file.open("myfile.txt");
// write to the file
file << "Welcome to C++ file streams. \n";
file << "Enjoy Learning!";
// close the file
file.close();
return 0;
}
When we run the program, it will not generate any output but will write the two lines of texts to the given file “myfile.txt“.
Example 5. Read from a file
To read from a file, use either the ifstream
or fstream
class, and specify the name of the file.
To read from the file, we need to use a while
loop together with the getline()
function (which belongs to the ifstream
class) to read the file line by line, and to print the content of the file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// open a file in read mode
ifstream file;
file.open("myfile.txt");
// create a string to output the text file
string text;
// read from the file
while (getline (file, text)) {
// output the text from file
cout << text;
}
// close the file
file.close();
return 0;
}
Output:
Welcome to C++ file streams.
Enjoy Learning!
Example 6. Writing and Reading on a file
We use << and >> to write to and read from a file respectively. Let us see an example. We also use the mode parameter while opening the file.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// create a char array as buffer
char info[50];
// open a file for writing
ofstream ofile;
ofile.open("example.txt");
// write to the file
cout << "Writing to the file:~ " << endl;
cout << "Dear student, enter your name: ";
cin.getline(info, sizeof(info));
ofile << info << endl;
cout << "Enter your roll: ";
cin >> info;
cin.ignore();
ofile << info << endl;
cout << "Enter your stream: ";
cin.getline(info, sizeof(info));
ofile << info << endl;
// close the file
ofile.close();
// open a file for reading
ifstream ifile;
ifile.open("example.txt");
// read from the file
string str;
cout << "\nReading from the file:~ " << endl;
while (getline (ifile, str)) {
cout << str << endl;
}
// close the file
ifile.close();
return 0;
}
The above example makes use of functions from cin object, such as getline() function for reading the line from the outside and ignore() function for nullifying the effect of extra characters created by the previous read operation.
Output:
Writing to the file:~
Dear student, enter your name: Suman Basu
Enter your roll: 32
Enter your stream: CSE
Reading from the file:~
Suman Basu
32
CSE