You are on page 1of 13

Object Oriented

Programming With C++

Click to add Text


Working with files

Click to add Text


Files
 fstream is an interface between program & the
file.
 Ifstream extracts instructions from file (>>).
 ofstream inserts instructions into file (<<).
 There are 2 formats of file operation
1. Text format :only char data.
2. Binary format.
Text format
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
int num[ ]={5,7,11,13,19};
ofstream fout("test.txt");
for(int i=0;i<5;i++)
fout<<num[i]<<endl;
return 0;
}
Another example
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin("test.txt");
int x;
while(1)
{
fin>>x;
if(fin.eof()) break;
cout<<x<<endl;
}
return 0;
}
get & put pointer
 Theoretically, get pointer should move as
we take input from a file & put pointer
should move as we write to a file. But
practically, get & put pointers move
together.
Four relevant functions are-
1. seekg: Moves the get pointer to a specified byte.
2. seekp: Moves the put pointer to a specified byte.
3. tellg: Tells the present position (byte no.) of get
pointer.
4. tellp: Tells the present position (byte no.) of put
pointer.
 In file, counting of bytes starts from zero (0).
 Here, present position means next byte to read
or write.
 In a single file, at a time more than one file
object/pointer should not work.
Example
int main() Output:
{
ofstream fout("test2.txt");
fout<<10<<endl; 10
fout.close(); 0
ifstream fin("test2.txt"); 2
int x;
fin>>x;
cout<<x<<endl;
fin.seekg(1);
fin>>x;
cout<<x<<endl;
cout<<fin.tellg()<<endl;
return 0;
}
Binary or Text format?
Storing 2594 in different formats
Text mode:
2 5 9 4 4 bytes

Binary mode:
00001010 00100010

2 bytes
Binary format
 Binary files are machine readable format,
not human readable format.
 Binary files take less space.
 Objects can be saved & retrieved
efficiently.
Operations in binary mode
int main()
class item
{
{
item t[10],temp;
int id;
t[0]=item(1,"A",50);
char name[100];
t[1]=item(2,"B",55.25);
double price;
fstream file
public:
("a.txt",ios::binary | ios::in | ios::out |
item(int i=0,char *n="N/A",double p=0) ios::app);
{
id=i; int i;
price=p; for(i=0;i<10;i++)
strcpy(name,n); file.write((char*)&t[i],sizeof(item));
} file.seekg(sizeof(item)*1,ios::beg);
file.read((char*)&temp,sizeof(item));
void show() temp.show();
{ return 0;
cout<<id<<" "<<name<< }
" "<<price<<endl;
} Output:
}; 2 B 55.25
Pointer offset call
 file.seekg(5,ios::beg);
 file.seekg(-5,ios::beg);
 file.seekg(5,ios::cur);
 file.seekg(-5,ios::cur);
Error handling functions
 file.fail();
 file.good();
 file.bad();

You might also like