Wednesday, 30 May 2012


DOWNLOAD FILEOPERATION.CPP FILE FROM HERE

VISIT MY SITE LIFEQUEST


Hi friends,
Let's have some fun with file operation in c++.

when we create class we usually need some method in our program to store objects's variable for use at a layer time , C++ provides file operation like input/output , EOF that is asking if file end is reached ,SEEKG that is get the length of the file and seekp set position for putting values.

Explore file operation in depth in C++

Have a look at following statement that creates ofstream object for writing in the file :
ofstream ofile("file.txt",ios::out);
Now look this one below this is used for reading values from files:
        ifstream ifile; 
        ifile.open("file.txt",ios::in);
here we have created object for reading from file .

Now since we need to directy store object of class we need sizeof operator to find out how many memory is occupied by object:

For writing in the file:
        ofile.write((char *)&obj,sizeof obj);  

For reading from file:
ifile.read((char *)&obj,sizeof obj);

now below is complete code for program that you can download from here.


SOURCE CODE:

#include <fstream.h>
#include <conio.h>
#include <string.h>
class me
{
int rollno;
char name[25];
public:
void getdata(int rno,char *n)
{
rollno = rno;
strcpy(name,n);
}
void display()
{
cout<<"Roll No = "<<rollno<<"\n";
cout<<"Name = "<<name<<"\n";
}

};

int main()
{
char *nm;
int rn;
clrscr();
ofstream ofile("file.txt",ios::out);
me obj;
cout<<"Enter roll noof student";
cin>>rn;
cout<<"Enter Name noof student";
cin>>nm;
obj.getdata(rn,nm);
ofile.write((char *)&obj,sizeof obj);
ofile.close();
ifstream ifile;
ifile.open("file.txt",ios::in);
ifile.read((char *)&obj,sizeof obj);
obj.display();
getch();
return 0;
}

So that is the program for file operation , below is the output of above program

Download program from here:

No comments:

Post a Comment