A
astral-blade
Guest
there is a file(test.txt) in which to write objects(instances of personally created class "record").
I plan to use a member of my record class: "int user_id" as the key. Then i use this as ((user_id-1)*sizeof(obj)) --[obj is the instance of record.] to get the position in the file where to insert this object. So,similar to array indices, i have user_id as the indirect source for direct access to a location where the object is stored.
I actually tried doing it and my code is :
#include<iostream>
using namespace std;
#include<fstream>
#include<cstring>
class record
{
int user_id;
string username;
string occupation;
public:
void setData(int k,string name,string occ)
{
user_id=k;
username=name;
occupation=occ;
}
void writeData()
{
cout<<user_id;
cout<<username;
cout<<occupation;
}
}obj;
int main()
{
obj.setData(4,"raman","job");
ofstream fout;
fout.open("test.txt",ios::app)
fout.seekp((4-1)*(sizeof(obj)),ios::beg); //in general however, there can be a user_id instead of 4
fout.write((char*)&obj,sizeof(obj)); //I expect it to write by skipping 3 locations(of the size of objs) and then write the object
ifstream fin;
fin.open("test.txt");
fin.seekg(((4-1)*sizeof(obj)),ios::beg);
obj.writeData();
return 0;
}
It compiles ok, but in the file, the objects are stored sequentially NOT at the specified location(i.e. in present case it wrote the object just at the beginning of the file(at position 0)) and when i search(as in code), it returns 0(not the information of any obj)
Please help
Continue reading...
I plan to use a member of my record class: "int user_id" as the key. Then i use this as ((user_id-1)*sizeof(obj)) --[obj is the instance of record.] to get the position in the file where to insert this object. So,similar to array indices, i have user_id as the indirect source for direct access to a location where the object is stored.
I actually tried doing it and my code is :
#include<iostream>
using namespace std;
#include<fstream>
#include<cstring>
class record
{
int user_id;
string username;
string occupation;
public:
void setData(int k,string name,string occ)
{
user_id=k;
username=name;
occupation=occ;
}
void writeData()
{
cout<<user_id;
cout<<username;
cout<<occupation;
}
}obj;
int main()
{
obj.setData(4,"raman","job");
ofstream fout;
fout.open("test.txt",ios::app)
fout.seekp((4-1)*(sizeof(obj)),ios::beg); //in general however, there can be a user_id instead of 4
fout.write((char*)&obj,sizeof(obj)); //I expect it to write by skipping 3 locations(of the size of objs) and then write the object
ifstream fin;
fin.open("test.txt");
fin.seekg(((4-1)*sizeof(obj)),ios::beg);
obj.writeData();
return 0;
}
It compiles ok, but in the file, the objects are stored sequentially NOT at the specified location(i.e. in present case it wrote the object just at the beginning of the file(at position 0)) and when i search(as in code), it returns 0(not the information of any obj)
Please help
Continue reading...