0% found this document useful (0 votes)
57 views10 pages

File Handling in CPP

1. The document discusses file handling in C++ using header files like <iostream> and <fstream>. 2. It describes classes like fstream, ifstream, and ofstream that allow opening, reading, and writing to files. 3. Examples are provided to demonstrate creating files and writing text to them using ofstream, as well as reading file contents using ifstream.

Uploaded by

subodh kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
57 views10 pages

File Handling in CPP

1. The document discusses file handling in C++ using header files like <iostream> and <fstream>. 2. It describes classes like fstream, ifstream, and ofstream that allow opening, reading, and writing to files. 3. Examples are provided to demonstrate creating files and writing text to them using ofstream, as well as reading file contents using ifstream.

Uploaded by

subodh kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

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.

Let’s understand with the help of example –


Example – create a text file (testout.txt) and write some information to that file.
#include <iostream>
#include <fstream>
using namespace std;

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.

Example - cpp program to read information file existing fie.


#include <iostream>
#include <fstream>
using namespace std;

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;

// write infomration to file


out_stream << "Name : " << name << endl << "Roll : " << roll << endl << "City : " << city <<
endl;
out_stream.close();

// read information from file


ifstream in_stream("test.txt", ios::in);
string line;
while(getline(in_stream, line)){
cout << line << endl;
}
in_stream.close();
return 0;
}
In this example, we write a program that accept input from user write information to file. After that this program read
information from file display output on console.
The cin is an object that is used to take input from user but it does not allow to take input in multiple lines. To accept multiple
lines, we use the getline() function. It is pre-define function available in <cstring> header file.
There are two following types of syntax for getline() –
istream &getline(istream &is, string &str, char delim);
here,
is  It is an object of input stream from where to read data.
str  It is an string object to store data after reading data.
delim  It is delimiting character.

Following is the another syntax –


Istream &getline(istream &is, string &str);
This function returns input stream object, which is passed as a parameter to the function.
Let’s understand with the help of example –
Example – 1
#include <iostream>
#include <cstring>
using namespace std;

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.

getline() function with character array


getline() is also used to deal with character array. Its syntax is also different from above syntax
istream &getline(char *, int size);
here,
char *  it is a character pointer that point to character array.
size  It acts as delimiter that defines the size of array means input cannot cross this size.
Example –
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char sent[50];
cout << "Enter sentence : " << endl;
cin.getline(sent, 50);
cout << "Your sentence : " << sent;
return 0;
}

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

let’s understand with the help of example –


example – cpp program to read data from file character by character.
#include <iostream>
using namespace std;
int main(){
FILE *file;
file = fopen("fgetc.cpp", "r");
while(1){
char ch = fgetc(file);
if(ch == EOF) // EOF --> showing End of file.
break;
cout << ch;
}
fclose(file);
return 0;
}

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.

Example – use of fscanf() 


this function reads set of character from file and returns EOF at the end of file. Following is
the syntax –
int fscanf(FILE *stream, const char *format, [arguments]);
#include <iostream>
using namespace std;

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

Another example – use of rewind(), fseek()


#include <iostream>
using namespace std;

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;
}

Serialization and de-serialization


Serialization is a process through which an object converted into stream of bytes to be stored in the disk or send to another
computer through network. And vice-versa of this process is called de-serialization.
In c++ there are two important functions are available for this purpose – read() and write().
read()  This function available in ifstream class.
write()  this function available in ofstream class.
Inside fstream class read() an write() both are available.
Syntax –
read((char *)&object, sizeof(class));
write((char *)&object, sizeof(class));
let’s understand with the help of example –
// example of object serialization
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Student{
char name[40];
int roll;
char city[20];

public:
void putdata();
};

void Student :: putdata(){


cout << "Enter your name : " << endl;
cin.getline(this->name, 40);

cout << "Enter roll number : " << endl;


cin >> this->roll;
cin.ignore();

cout << "Enter your city name : " << endl;


cin.getline(this->city, 20);
}

int main(){

ofstream out_stream;
out_stream.open("student.txt", ios::out); // create file for writing

Student std_obj;
std_obj.putdata();

out_stream.write((char *)&std_obj, sizeof(Student)); // here, serialization is happen


out_stream.close();

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.

Example – example of de-serialization


// example of de-serialization
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

class Student{
private:
char name[40];
int roll;
char city[20];

public:
void getdata();
};

void Student :: getdata(){


cout << "Name : " << this->name << endl;
cout << "Roll : " << this->roll << endl;
cout << "City : " << this->city << endl;
}

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.

You might also like