can data structures and file handling be merged (using data structures within files or...

  • Thread starter Thread starter astral-blade
  • Start date Start date
A

astral-blade

Guest
i have a file(.txt) in which i write objects(instances of personally created class "record"). But i wish to store these objects in the file on the basis of a hash function(in normal case, we would store records on the indices of an array using hash function).

But the problem is how do i implement this approach within files. I plan to use a member of my record class: "int user_id" as the key to the hash function which would return me user_id%100. Then i use this as ((pos-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 key;
string username;
string occupation;
public:
void getData(int k,string name,string occ)
{
key=k;
username=name;
occupation=occ;
}
void putData()
{
cout<<key;
cout<<username;
cout<<occupation;
}
}obj;
int hashh(int key)
{
return key%100;
}

int main()
{
obj.getData(104,"raman","job");
ofstream fout;
fout.open("test.txt",ios::app);
int pos = hashh(104);//return 4

fout.seekp((pos-1)*(sizeof(obj)),ios::beg);
fout.write((char*)&obj,sizeof(obj));
ifstream fin;
fin.open("test.txt");
fin.seekg(((4-1)*sizeof(obj))-1,ios::beg);
obj.putData();
return 0;
}

It compiles ok, but in the file, the objects are stored sequentially NOT at the specified location and when i search(as in code), it returns 0.

Please help to fix it or give an alternative approach on implementing data structures such as trees or hash with files.

Continue reading...
 
Back
Top