The read function has it's first argument as pointer to an array to store the n bytes(mentioned by the second argument) in the file...
The query is,
if i have created 2 objects of class x..
then,
x stack[2];
Assume i've filled the 2 object contents, opened a file 'xyz'(using fstream i've created object file & used the command file.open("xyz",ios::in|ios::out)
and filled the file with contents of 2 objects using write..
now if i use this command
file.read((char*) &stack[1],sizeof(stack[0]))
will the stack[1]
have the contents of stack[0]
,
i.e. will the read function take it's first argument address as &stack[1]
or will it consider &stack[0]
??
Update:The code which is used to reverse the contents of the stack
// //To reverse the contents of the objects
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
class Inventory
{
char name[10];
int code;
int cost;
public:
void readdata();
void writedata();
};
void Inventory::readdata(void)
{
cin>>name;
cin>>code;
cin>>cost;
}
void Inventory::writedata(void)
{
cout<<setiosflags(ios::left)
<<setw(10)<<name
<<resetiosflags(ios::right)
<<setw(10)<<code
<<setprecision(2)
<<setw(10)<<cost
<<endl;
}
int main()
{
Inventory item[3];
fstream file;
file.open("Stock",ios::in|ios::out);
cout<<"Enter details for three items\n";
for(int i=0;i<3;i++)
{
item[i].readdata();
file.write((char*) &item[i],sizeof(item[i]));
}
file.seekg(0);
cout<<"\nOutput\n\n";
for(int i=0;i<3;i++)
{
file.read((char*) &item[2-i],sizeof(item[i]));
}
for(int i=0;i<3;i++)item[i].writedata();
file.close();
return 0;
}
Try this:
file.open("Stock",ios::in|ios::trunc|ios::out);