C++ : File I/O Part 3

1. Explain the use of File I/O.

2. Read and Write Object & Array using:

1. read()

2. write()

3. Explain the use of following method:

1. seekg()

2. tellg()

3. seekp()

4. tellp()

4. Example showing the use of reading & writing data into the File.


/*
Developed By: Prof. Vinod Pillai
vinodthebest@gmail.com
C++ File I/O - Part 3.
*/

#include
#include

using namespace std;

class Employee
{
int id;
int salary;

public:

Employee(){ }
~Employee(){ }

void setData()
{
cout<>id;
cout<>salary;
}

void display()
{
cout<<“\n ID:”<<id;
cout<<“\n Salary:”<<salary;
}
};

int main()
{
int arr[]={10,20,30,40,50};

//Writing Array values.
fstream fobj(“one.dat”,ios::out);

fobj.write((char *)&arr,sizeof(arr));

fobj.close();

//Reading Array values.
fobj.open(“one.dat”,ios::in);

int arr2[5];

fobj.read((char *)&arr2,sizeof(arr2));

for(int i=0;i<5;i++)
{
cout<<arr2[i]<<“\n”;
}

fobj.close();

//Writing Object value.

fobj.open(“one.dat”,ios::out);

Employee e1;

e1.setData();

fobj.write((char *)&e1,sizeof(e1));

fobj.close();

//Reading Object value.

fobj.open(“one.dat”,ios::in);

Employee e2;

fobj.read((char *)&e2,sizeof(e2));

e2.display();

fobj.close();

return 0;
}

Advertisements

1 Comment

Filed under C++, File I/O

One response to “C++ : File I/O Part 3

  1. programmer

    just what i wanted! Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s