0% found this document useful (0 votes)
46 views

File Handling in C++: Objective: To Insert Some Data On A Text File

Files are used to store data permanently as RAM cannot. C/C++ treats all devices like keyboard, mouse etc as files. There are two main types - text and binary files. Both need to be opened and closed using functions like open(), close(). To read/write from files, functions like read(), write() are used. Class objects can also be written to and read from files by writing/reading the entire object using its size.

Uploaded by

Ritik Madaan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

File Handling in C++: Objective: To Insert Some Data On A Text File

Files are used to store data permanently as RAM cannot. C/C++ treats all devices like keyboard, mouse etc as files. There are two main types - text and binary files. Both need to be opened and closed using functions like open(), close(). To read/write from files, functions like read(), write() are used. Class objects can also be written to and read from files by writing/reading the entire object using its size.

Uploaded by

Ritik Madaan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

File Handling in C++

Files are required to save our data for future use, as Ram is not able to hold our data permanently.

Files

Data Files
Program Files

Text Files Binary Files

The Language like C/C++ treat every thing as a file , these languages treat keyboard , mouse, printer, Hard
disk , Floppy disk and all other hardware as a file.

The Basic operation on text/binary files are : Reading/writing ,reading and manipulation of data stored on
these files. Both types of files needs to be open and close.

How to open File


Using member function Open( ) Using Constructor
Syntax Syntax
Filestream object; Filestream object(“filename”,mode);
Object.open(“filename”,mode);
Example Example
ifstream fin;
fin.open(“abc.txt”) ifstream fin(“abc.txt”);

NOTE: (a) Mode are optional and given at the end .


(a) Filename must follow the convention of 8.3 and it’s extension can be anyone

How to close a file


All types of files can be closed using close( ) member function
Syntax
fileobject.close( );
Example
fin.close( ); // here fin is an object of istream class

Objective : To insert some data on a text file

Program file SCR

Abc.txt

Program

Page 1 of 10
Program ABC.txt file contents
#include<fstream> This is my first program in file handling
using namespace std; Hello again
int main()
{
ofstream fout;
fout.open("abc.txt");
fout<<"This is my first program in
file handling";
fout<<"\n Hello again";
fout.close();
return 0;
}

Reading data from a Text File


Screen
Keyboard Program

ABC.TXT

#include<fstream>
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
char str[80];
fin.open("abc.txt");
fin>>str; // read only first
//string from file
cout<<"\n From File :"<<str; // as
//spaces is treated as termination point
getch();
return 0;
}
NOTE : To overcome this problem use
fin.getline(str,79);

Detecting END OF FILE


Using EOF( ) member function Using filestream object
Syntax Example
Filestream_object.eof( ); // detectting end of file
Example #include<iostream>
#include<iostream> #include<fstream>
#include<fstream> #include<conio.h>
#include<conio.h> using namespace std;
using namespace std; int main()
{
int main()
{ char ch;
char ch; ifstream fin;
ifstream fin; fin.open("abc.txt");
while(fin) // file object
fin.open("abc.txt");

Page 2 of 10
while(!fin.eof()) // using eof() {
// function fin.get(ch);
{ cout<<ch;
fin.get(ch); }
cout<<ch; fin.close();
} getch();
fin.close(); return 0;
getch(); }
return 0;
}

Example : To read the contents of a text file and display them on the screen.
Program ( using getline member function) Program ( using get( ) member function)
#include<fstream> #include<fstream>
#include<conio.h> #include<conio.h>
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
char str[100]; char ch;
ifstream fin; ifstream fin;
fin.open("c:\\abc.txt"); fin.open("file6.cpp");
while(!fin.eof()) while(!fin.eof())
{ {
fin.getline(str,99); fin.get(ch);
cout<<str; cout<<ch;
} }
fin.close(); fin.close();
getch(); getch();
return 0; return 0;
} }

Writing/Reading Data in Binary Format

To write and read data in binary format two member functions are available in C++. They are read( ) and
write( ).
Syntax for Write( ) member
function
Fileobject.write( (char *)&object, sizeof(object));

Fileobject.read( (char *)&object, sizeof(object)); Syntax for read( ) member


function
Example of write ( ) member function
Program Output
#include<fstream>
#include<iostream>
using namespace std;
struct student
{
int roll ;
char name[30];
char address[60];
};
int main()
{
student s;
ofstream fout;
fout.open("student.dat");
cout<<"\n Enter Roll Number :";
cin>>s.roll;
cout<<"\n Enter Name :";

Page 3 of 10
cin>>s.name;
cout<<"\n Enter address :";
cin>>s.address;
fout.write((char *)&s,sizeof(student));
fout.close();
return 0;
}

To Read data from a binary File using read( ) member function


Program using read( ) member function output
#include<fstream>
#include<iostream>
#include<conio.h>
using namespace std;
struct student
{
int roll ;
char name[30];
char address[60];
};
int main()
{
student s;
ifstream fin;
fin.open("student.dat");
fin.read((char *)&s,sizeof(student));
cout<<"\n Roll Number :"<<s.roll;
cout<<"\n Name :"<<s.name;
cout<<"\n Address :"<<s.address;
fin.close();
getch();
return 0;
}

Writing Class object in a file

#include<fstream>
#include<iostream>
using namespace std;
class student
{
int roll ;
char name[30];
char address[60];
public:
void read_data( ); // member function prototype
void write_data( ); // member function prototype

};
void student::read_data( ) // member function defintion
{
cout<<"\n Enter Roll :";
cin>>roll;
cout<<"\n Student name :";
cin>>name;
cout<<"\n Enter Address :";
cin>>address;
}
void student:: write_data()
{
cout<<"\n Roll :"<<roll;
cout<<"\n Name :"<<name;
cout<<"\n Address :"<<address;
}
int main()
{

Page 4 of 10
student s;
ofstream fout;
fout.open("student.dat");
s.read_data(); // member function call to get data from KBD
fout.write((char *)&s,sizeof(student)); // write object in file
fout.close();
return 0;
}

Reading Class object from a binary file


#include<fstream>
#include<iostream>
#include<conio.h>
using namespace std;
class student
{
int roll ;
char name[30];
char address[60];
public:
void read_data( ); // member function prototype
void write_data( ); // member function prototype

};
void student::read_data( ) // member function defintion
{
cout<<"\n Enter Roll :";
cin>>roll;
cout<<"\n Student name :";
cin>>name;
cout<<"\n Enter Address :";
cin>>address;
}
void student:: write_data()
{
cout<<"\n Roll :"<<roll;
cout<<"\n Name :"<<name;
cout<<"\n Address :"<<address;
}
int main()
{
student s;
ifstream fin;
fin.open("student.dat");
fin.read((char *)&s,sizeof(student));
s.write_data();
fin.close();
getch();
return 0;
}

some other very important member function


Member function Explanation
name
seekg( ) Used to move reading pointer forward and backward
Syntax
fileobject.seekg( no_of_bytes,mode);

Page 5 of 10
Example:
(a) fout.seekg(50,ios::cur); // move 50 bytes forward from current position
(b) fout.seekg(50,ios::beg); // move 50 bytes forward from current beginning
(c) fout.seekg(50,ios::end); // move 50 bytes forward from end .

seekp( ) Used to move writing pointer forward and backward


Syntax
fileobject.seekp(no_of_bytes,mode);
Example:
(a) fout.seekp(50,ios::cur); // move 50 bytes forward from current position
(b) fout.seekp(50,ios::beg); // move 50 bytes forward from current beginning
(c) fout.seekp(50,ios::end); // move 50 bytes forward from end .
tellp( ) It return the distance of writing pointer from the beginning in bytes
Syntax
Fileobject.tellp( );
Example:
long n = fout.tellp( );
tellg( ) It return the distance of reading pointer from the beginning in bytes
Syntax
Fileobject.tellg( );
Example:
long n = fout.tellg( );

Files MODES
File mode Explanation
ios::in Input mode – Default mode with ifstream and files can be read only
ios::out Output mode- Default with ofstream and files can be write only
ios::binary Open file as binary
ios::app Preserve previous contents and write data at the end ( move forward only)
ios::ate Preserve previous contents and write data at the end.( can move forward and
backward )
ios::nodelete Do not delete existing file
ios::noreplace Do not replace file
ios::nocreate Do not create file

NOTE : To add more than one mode in a file stream use bitwise OR ( | ) operator
Example :

Difference and Definition_____________________________________________________


Text Files Binary Files
In these types of files all the data is firstly converted into In these types of files all the data is stored in the binary
their equivalent char and then it is stored in the files. format as it is stored by the operating system. so no
conversion takes place. Hence the processing speed is
much more than text files.

get( ) member function getline() function


Get() function is used to read a single char Getline() function is used to read a string from the input
from the input stream in text file stream in text file.
Syntax Syntax
fileobject.get(char); fileobject.getline (string, no_of_char, delimiter );
Example: Example
Fin.get(ch); //fin is file stream. fin.getline(str,80); // fin is file stream.

Page 6 of 10
NOTE: Delimiter is optional

Put( ) member Function Write( ) member Function


Put( ) function is used to write a single char into Write member function is used to write data into
output stream in a text mode output stream in binary mode

Program to Explain the different operation for Project

#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
class student
{
int admno;
char name[30];
char address[60];
public:
void read_data()
{
cout<<"\n Enter Admission No :";
cin>>admno;
fflush(stdin);
cout<<"\n Enter Name :";
cin.getline(name,29);
fflush(stdin);
cout<<"\n Enter Address :";
cin.getline(address,59);
}
void write_data()
{
cout<<"\n\n Admission No :"<<admno;
cout<<"\n Name :"<<name;
cout<<"\n Address :"<<address;
}
int get_admno()
{
return admno;
}
};

void write_to_file(void)
{
student s;
ofstream fout;
fout.open("student.dat",ios::app);
s.read_data();
fout.write((char *)&s,sizeof(student));
fout.close();
return;
}
void read_from_file()
{
student s;
ifstream fin;
fin.open("student.dat");
while(fin.read((char *)&s,sizeof(student)))
s.write_data();
fin.close();
return;
}

Page 7 of 10
// function to modify student information

void modify_record(void)
{
int temp_admno;
student s;
ifstream fin;
ofstream fout;
fin.open("student.dat");
fout.open("temp.dat");
system("cls"); // header file stdlib.h
cout<<"\n Enter admission No to Modify :";
cin>>temp_admno;
while(fin.read((char *)&s,sizeof(student)))
{
if (temp_admno==s.get_admno())
{
s.read_data();
}
fout.write((char *)&s,sizeof(student));
}
fin.close();
fout.close();
remove("student.dat");
rename("temp.dat","student.dat");
return;
}

void modify_alternate_method()
{
student s;
int temp_admno;
fstream file;
file.open("student.dat",ios::in|ios::out|ios::ate|ios::binary);
cout<<"\n Enter admno to modify :";
cin>>temp_admno;
file.seekg(0); // one method to reach at begining

// long n = file.tellg(); // find out total no of bytes


// file.seekg((-1)*n,ios::end); // move backward total no of bytes from end

while(file.read((char*)&s,sizeof(student)))
{
if(temp_admno == s.get_admno())
{
s.read_data();
int n = -1*sizeof(student);
file.seekp(n,ios::cur);
file.write((char *)&s,sizeof(student));
}
}
file.close();
return;
}

void delete_record(void)
{
int temp_admno;
student s;
ifstream fin;
ofstream fout;
fin.open("student.dat");
fout.open("temp.dat");
system("cls");
cout<<"\n Enter admission No to Delete :";
cin>>temp_admno;

Page 8 of 10
while(fin.read((char *)&s,sizeof(student)))
{
if (temp_admno!=s.get_admno())
fout.write((char *)&s,sizeof(student));
}
fin.close();
fout.close();
remove("student.dat"); // stdio.h
rename("temp.dat","student.dat"); // stdio.h
return;
}

void search_record()
{
int found=0;
student s;
int temp_admno;
ifstream fin("student.dat");
cout<<"\n Enter Admno to search :";
cin>>temp_admno;
while(fin.read((char*)&s,sizeof(student)))
{
if(temp_admno==s.get_admno())
{
found=1;
s.write_data();
}
}
fin.close();
if(found ==0)
cout<<"\n Admission No. "<<temp_admno<<" does not exist ";
getch();
return;
}

void count_record(void)
{
int count=0;
student s;
int temp_admno;
ifstream fin("student.dat");
while(fin.read((char*)&s,sizeof(student)))
count++;
fin.close();
cout<<"\n Total Record :"<<count;
getch();
return ;
}

int main()
{
int choice;
do
{
system("cls"); // stdlib.h
cout<<"\n\n\t\t\t MAIN MENU ";
cout<<"\n\t\t\t\t1. Add Student ";
cout<<"\n\t\t\t\t2. Show Student";
cout<<"\n\t\t\t\t3. Modify Record";
cout<<"\n\t\t\t\t4. Modify Record (Alternate Method)";
cout<<"\n\t\t\t\t5. Delete Record";
cout<<"\n\t\t\t\t6. Count Record";
cout<<"\n\t\t\t\t7. Search Record";
cout<<"\n\t\t\t\t8. Exit";
cout<<"\n\n\t\t\t\t Enter your choice :";

Page 9 of 10
cin>>choice;
switch(choice)
{
case 1: system("cls");
write_to_file();
break;
case 2:
read_from_file();
getch();
break;
case 3:
modify_record();
break;
case 4:
modify_alternate_method();
break;
case 5:
delete_record();
break;
case 6: count_record();
break;
case 7: search_record();
break;
case 8:
break;

default:
cout<<"\n Wrong choice.... Try again";
getch();
}
}while(choice!=8);
return 0;
}

Page 10 of 10

You might also like