File Handling in C++: Objective: To Insert Some Data On A Text File
File Handling in C++: Objective: To Insert Some Data On A Text File
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
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.
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;
}
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);
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;
} }
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));
Page 3 of 10
cin>>s.name;
cout<<"\n Enter address :";
cin>>s.address;
fout.write((char *)&s,sizeof(student));
fout.close();
return 0;
}
#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;
}
};
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;
}
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 .
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 :
Page 6 of 10
NOTE: Delimiter is optional
#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
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