Object Filing in C++
Stream Class Hierarchy:
Creating File Object:
fileClassName fileObjectName (“FileName”, mode);
C++ className for filing:
ofstream Stream class for writing data in files (default mode is ios::out)
ifstream Stream class for reading data in files (default mode is ios::in)
fstream Stream class for both above (default mode is ios::out|
ios::in)
Note: if we add any mode in fstream then default overrides
C++ mode for filing:
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
Set the initial position at the end of the file.
ios::ate
If this flag is not set, the initial position is the beginning of the file.
All output operations are performed at the end of the file, appending the content
to the current content of the file.
ios::app
Difference with ios::ate: You cannot move the writing pointer to any other
location; even if you use seekp() to change the position. Best for log files.
If the file is opened for output operations and it already existed, its previous
content is deleted and replaced by the new one.
ios::trunc
Difference with default: for ofstream object it is same but for fstream object
default mode will not truncate.
Opening a File:
fstream file(“D://UIIT//[Link]”, ios::out| ios::in| ios::binary| ios::app);
OR
fstream file;
[Link](“D://UIIT/[Link]”, ios::out| ios::in| ios::binary| ios::app);
Closing a File:
[Link]();
Data Flush to file without closing file:
[Link]();
File Object connection with File:
if (! file.is_open ()) {/* file stream not opening a file */}
File stream state flags:
bad()
Returns true if a reading or writing operation fails. For example, in the case that we
try to write to a file that is not open for writing or if the device where we try to write
has no space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error
happens, like when an alphabetical character is extracted when we are trying to read
an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any
of the previous functions would return true. Note that good and bad are not exact
opposites (good checks more state flags at once).
clear()
The member function clear() can be used to reset the state flags.
Read Pointers:
streampos position=tellg(); //return the position of read pointer
Note: std::streampos is a class type designed to represent positions in streams (like
files). streampos is not int, it internally handles complex position states (like multibyte
characters and locale-specific considerations).
seekg(position); //change the position of read pointer at a specific location
OR
seekg(position, direction); //direction may be: ios::beg
// ios::curr
// [Link](6, ios::curr); means move 6Byte forward from curr
// ios::end
//[Link](-5, ios::end); means move to 5th byte from the end
Write Pointers:
streampos position= tellp(); //return the position of write pointer
seekp(position); //change the position of write pointer at a specific location
OR
seekp(position, direction);
Example:
[Link]([Link]() - sizeof(this));
//relocating the position of write pointer one object back from the
//current position of read pointer, where this means calling object.
Writing Data in file for calling object:
[Link]((char *)this, sizeof(*this));
Reading Data from file for calling object:
[Link]((char *)&Student, sizeof(Student));
Example Code:
//Tested on Visual Studio 2015
#include"stdafx.h"
#include<iostream>
#include<conio.h>
#include<fstream>
#include<stdio.h> //for dos remove and rename command
using namespace std;
class Student
{
int rollno;
char name[20];
public:
void getData()
{
cout << "\nEnter Roll No;"; cin >> rollno;
cout << "Enter First Name:"; cin >> name;
}
void showData()
{
cout << "\n" << rollno << "\t" << name;
}
void writeFile()
{
fstream file("[Link]", ios::binary | ios::out | ios::app);
if (!file)
cout << "\nFile Writing Object Error....";
else
{
getData();
[Link]((char*)this, sizeof(*this));
cout << "\nThe following record added successfully";
cout <<"\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&";
cout << "\nRoll No\tFirst Name:";
cout << "\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&";
showData();
}
[Link]();
}
void readFile()
{
int count = 0;
fstream file("[Link]", ios::binary | ios::in);
if (!file)
cout << "File reading error....";
else
{
cout << "\nFollowing are the Records from File";
cout << "\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&";
cout << "\nRoll No\tFirst Name:";
cout << "\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&";
[Link]((char*)this, sizeof(*this));
while (![Link]())
{
count++;
showData();
[Link]((char*)this, sizeof(*this));
}
cout<<"\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&";
}
if(count==0)
cout<<"\nRecord not found";
else
cout<<"\nTotal Records found="<<count;
[Link]();
}
void searchFile()
{
fstream file("[Link]",ios::binary|ios::in);
if(!file)
cout<<"\nReading error";
else
{ cout<<"\nEnter Roll No you want to search:";
int r; int count=0;
cin>>r;
[Link]((char*)this, sizeof(*this));
while(![Link]())
{
if(r==rollno)
{
showData();
count++;
}
[Link]((char*)this, sizeof(*this));
}
if(count==0)
cout<<"\nRecord not found";
else
cout<<"\nTotal Records found="<<count;
}
[Link]();
}
void updateRecord()
{
fstream file("[Link]",ios::binary|ios::in|ios::out);
/*we will not use ios::app because we need random updation,
however ios::app only allow updation after the eof
*/
if(!file)
cout<<"\nFile Reading error....";
else
{ cout<<"\nEnter Roll No you want to update:";
int r; int count=0;
cin>>r;
[Link]((char*)this, sizeof(*this));
while(![Link]())
{
if(r==rollno)
{
count++;
streampos rposition=[Link]();
int size=sizeof(*this);
[Link]((int)rposition - size);
getData();
[Link]((char*)this, sizeof(*this));
break; //removing one record at a time
}
[Link]((char*)this, sizeof(*this));
}
if(count==0)
cout<<"\nRecord not found";
else
cout<<"\n"<<count<<" Record updated successfully";
}
[Link]();
}
void deleteRecord()
{
fstream file("[Link]",ios::binary|ios::in|ios::out);
fstream tempfile("record_t.txt", ios::binary | ios::out);
if(!file)
cout<<"\nFile Reading error";
else
{
cout<<"\nEnter Roll No you want to delete:";
int r; int count=0;
cin>>r;
[Link]((char*)this, sizeof(*this));
while (![Link]())
{
if (r == rollno)
{
count++;
}
else
{
[Link]((char*)this, sizeof(*this));
}
[Link]((char*)this, sizeof(*this));
}
if (count == 0)
cout << "\nRecord not found";
else
{
cout << "\n" << count << " Record deleted successfully";
[Link]();
[Link]();
remove("[Link]");
rename("record_t.txt", "[Link]");
}
}
[Link]();
}
};
int main()
{
int option;
Student s1;
do
{
system("cls");
cout << "\n\tPress 1 for write data into file";
cout << "\n\tPress 2 for read data from file";
cout << "\n\tPress 3 for search data from file";
cout << "\n\tPress 4 for update record in file";
cout << "\n\tPress 5 for delete record from file:";
cout << "\n\tEnter Option:";
cin >> option;
switch (option)
{
case 1: [Link](); break;
case 2: [Link](); break;
case 3: [Link](); break;
case 4: [Link](); break;
case 5: [Link](); break;
}
cout << "\n\n\tDo you want to continue...y/n:";
} while (_getche() == 'y');
cout << "\n\tThanks for using this program, Bye!";
_getch();
return 0;
}