Iam trying to write the datas into file and then read from file and below is the program.
The data is being written in the file properly but there is some issue with read, i am unable to find where has it exactly gone wrong?
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
struct Stud {
int roll;
std::string name;
std::string fname;
};
int main(int argc, const char * argv[]) {
// insert code here...
std::ofstream myObj ;
myObj.open("/Users/tejas/Documents/cust.txt",std::ios::out|std::ios::binary|std::ios::app);
for(int i =1 ;i < 9 ; ++i)
{
std::stringstream buf;
Stud obj;
obj.roll = i *10;
buf << i<<"_"<<i*10;
buf >> obj.fname;
buf << i*10;
buf >> obj.name;
std::cout<<obj.fname<<obj.name<<obj.roll<<"\n";
myObj.write((char *)&obj, sizeof(Stud));
}
myObj.close();
std::ifstream myOp ;
Stud obj1;
myOp.open("/Users/tejas/Documents/cust.txt",std::ios::in|std::ios::binary);
std::vector< Stud> myVec;
while ( myOp.read( (char*)&obj1, sizeof(Stud) ) )
{
myVec.push_back(obj1);
}
myOp.close();
for (auto i : myVec)
{
std::cout<<i.fname<<i.name<<i.roll<<"\n";
}
return 0;
}
The output vector just have 0's and no values in it while print it Have i done it wrong while writng the file ? I can see some binary data in the file actually Thanks
Aucun commentaire:
Enregistrer un commentaire