File Handling in CPP
File Handling in CPP
In cpp programs, we use <iostream> header file that provides cin and cout objects for reading input and display output
respective.
In cpp library there is another header file that provides methods to perform operation on file that is <fstream>. This header
file is used for file handling program. File handling means perform operation on file like – open file, read file, write data on file
and close file, etc. following classes are available under <fstream> header file.
1. fstream It is used to create a file, write information to file and read information from file.
2. ifstream It is used to read information from file.
3. ofstream It is used to write information to file.
int main(){
ofstream file("testout.txt"); // create file for writing information
if(file.is_open()){
file << "Welcome to Cpp file handling programming" << endl;
file << "this is simple example.";
file.close();
}
else{
cout << "File opening is fail !" << endl;
}
return EXIT_SUCCESS;
}
When we execute this program then ‘testout.txt’ file is created and some information are written according to our program.
int main(){
ifstream filestream("testout.txt");
string str;
if(filestream.is_open()){
while(getline(filestream, str)){
cout << str << endl;
}
filestream.close();
}
else{
cout << "File opening is failed..";
}
return 0;
}
Example – cpp program to write information to file and read that information.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
string name;
int roll;
string city;
fstream out_stream("test.txt", ios::out);
cout << "enter your name : " << endl;
getline(cin, name);
cin.ignore();
cout << "Enter roll number : " << endl;
cin >> roll;
cin.ignore();
cout << "Enter your city's name : ";
cin >> city;
int main(){
string profile;
cout << "Enter your job profile --> ";
getline(cin, profile,' '); // here, ' ' (space) character act as delimitor.
cout << "Your job profile : " << profile;
return 0;
}
After executes this program we will get as below –
Enter your job profile
software developer
Your job profile : software
We can see that in getline() we pass space(‘ ‘) character as delimiter then after encountering delimiter getline() function does
not store data in variable. We can see in above example.
Example – 2
#include <iostream>
#include <cstring>
using namespace std;
int main(){
string name;
cout << "Enter your name " << endl;
getline(cin, name);
cout << "Hello ! " << name;
return 0;
}
When we execute this program then –
Enter your name :
Subodh kumar
Hello ! Subodh kumar
Here, we can see that when we does not pass any delimiter as third argument to getline() function then it store entire string as
input to specified variable.
Following are some important function that are frequently used in cpp. These functions are available from c library.
1. fopen() this function is used to open file.
2. fprintf() to write data into file
3. fscanf() read data from file
4. fputc() writes a character to file
5. fgetc() read a character from file
6. fclose() close the opened file
7. fseek() set the file pointer from current position to given position.
8. fputw() writes an integer to file
9. fgetw() read an integer from file.
10. ftell() return current position
11. rewind() set file pointer to beginning of the file
1. fopen()
syntax – *FILE fopen(“path/file_name”, “mode_of_file”);
mode_of_file it describe the state of file. It means files are open for which purpose like for reading purpose, writing
purpose or append data to file, etc.
followings are some important mode that are frequently used in cpp.
r open file for reading
w open file for writing
a open file for append data
r+ open file for reading and writing
w+ open file for reading and writing
rb open binary file for reading
wb open binary file for writing
ab open a binary file for append
rb+ open binary file for reading and writing
wb+ open binary file for reading and writing
Example – use of fprintf() this function writes set of character into file.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
FILE *file;
file = fopen("test.txt", "w"); // open/create file for writing data
fprintf(file, "This example demonstrate the use of fprintf function. ");
fclose(file);
return 0;
}
After executing program, a test.txt file is created and "This example demonstrate the use of fprintf function”
text is written.
int main(){
FILE *file;
file = fopen("test.txt", "r");
char buff[255]; // char array to store data of file
while(fscanf(file, "%s", buff) != EOF){
cout << buff;
}
fclose(file);
return 0;
}
Here, fscanf() function does not read space therefore, when we execute this file we will get all character from file without space. As
shown in the following –
Thisexampledemonstratetheuseoffprintffunction.
To solve this problem, we need to read character by character therefore, fgetc() can be used.
Example – use of fputc() this function is used to write character into file.
#include <iostream>
using namespace std;
int main(){
FILE *file;
file = fopen("file.txt", "w");
fputc('S', file); // write character to file
fclose(file);
return 0;
}
When we execute this program, a file.txt file is created and ‘S’ is written into that file.
Example – use of fgets() this function is used to read line of character from file.
#include <iostream>
using namespace std;
int main(){
FILE *file;
file = fopen("test.txt", "r");
char text[200];
fgets(text, 200, file); // here, 200 --> show number character to be read at a line from file.
cout << text;
return 0;
}
fseek() this function is used to set the file pointer to specified offset. With the help of this function we can write data at desire
location into the file.
Syntax –
int fseek(FILE *filestream, long int offset, int origin);
where
filestream file pointer that pointing to opened file.
offset number of character to displace from origin.
origin position used as reference to add the offset. It can have the following values.
SEEK_SET Beginning of the file.
SEEK_CUR current position of the file pointer.
SEEK_END end of file.
On the success fseek() returns zero(0) otherwise it returns non-zero.
Example –
#include <iostream>
using namespace std;
int main(){
FILE *file;
file = fopen("test.txt", "w+");
fputs("This is javatpoint", file);
fseek(file, 8, SEEK_SET);
fputs("sonoo jaiswal", file);
fclose(file);
return 0;
}
In this example, before the calling of fseek() data in text file is – “This is javatpoint”. But after calling fseek() data in text file is – “this
is sonoo jaiswal.” Because, from the beginning of file, file pointer moves 8 character forward by using fseek() and override the text
by fputs().
rewind() this function is used to set the cursor at the beginning of the file.
Syntax –
Void rewind(FILE *stream);
Let’s understand with the help of example –
#include <iostream>
using namespace std;
int main(){
FILE *file;
file = fopen("test.txt", "r");
char ch;
while((ch = fgetc(file)) != EOF){
printf("%c", ch);
}
rewind(file); // after reading the file, we set the cursor at the beginning of the file.
cout << endl;
while((ch = fgetc(file)) != EOF){
printf("%c", ch);
}
return 0;
}
Output
This is sonoo jaiswal
This is sonoo jaiswal
int main(){
FILE *file;
file = fopen("test.txt", "w+");
fputs("Erica 25 Berlin", file);
rewind(file); // set position at the beginning of the file.
char ch;
printf("Name : ");
while((ch = fgetc(file)) != ' ')
putchar(ch);
putchar('\n');
rewind(file);
fseek(file, 6, SEEK_SET); // skip the file pointer at 10 offset from beginning of the file.
printf("Age : " );
while((ch = fgetc(file)) != ' ')
putchar(ch);
putchar('\n');
rewind(file) ;
fseek(file, 9, SEEK_SET); // skip the file pointer at 15 offset from beginning of the file.
printf("City : ");
while((ch = fgetc(file)) != EOF)
putchar(ch);
putchar('\n');
fclose(file);
return 0;
}
Output –
Name : Erica
Age : 25
City : Berlin
ftell() this function is used to get the current position of the file pointer.
Syntax –
long int ftell(FILE *stream);
if this method encountered any error then it return -1 otherwise it return unsigned long int.
example –
#include <iostream>
using namespace std;
int main(){
FILE *file;
file = fopen("test.txt", "r");
int length = 0;
fseek(file, 0, SEEK_END); // set file pointer at the end of file.
length = ftell(file); //get the current position of file pointer.
fclose(file);
printf("\nSize of file : %d bytes", length);
return 0;
}
class Student{
char name[40];
int roll;
char city[20];
public:
void putdata();
};
int main(){
ofstream out_stream;
out_stream.open("student.txt", ios::out); // create file for writing
Student std_obj;
std_obj.putdata();
return 0;
}
This program simple example of serialization. In this program we insert input some information related to student into student
object and that object is serialized and stored information into text file.
class Student{
private:
char name[40];
int roll;
char city[20];
public:
void getdata();
};
int main(){
ifstream in_stream;
in_stream.open("student.txt", ios::in);
Student std_obj;
in_stream.read((char *)&std_obj, sizeof(Student)); // here, de-serialization happen
std_obj.getdata();
return 0;
}
In this example, we read the information of student from the text file stored that information into student’s object. So, in this
program de-serialization occurred. After storing into object this program display information on the console.