I'm having problems with the basics of binary file i/o. I really don't know too much about file i/o so far, so I'll try to describe my question as best I can.
What I'm trying to do is to create a simple hash file with 7 buckets while each bucket holds 2 entries and utilize them. So far, I been able to create a blank table, but I haven't been able to write to any of the buckets, at least in the way that I want to. I find the correct offset but the blank table gets wiped up until the point where I want to write and after it gets removed. I checked this with a hex editor.
So, what I think i want to ask is - how can I open a existing file to modify in binary? or how do i change one of the entries in the blank hash table/file?
I think what I've put in bold below is what has been causing my problems. I think im lost : /
thanks for any insight/advice.
(most of this is incomplete)
funcs.cpp
Code:
#include "func.h"
#include <iostream>
#include <fstream>
using namespace std;
HashFile::HashFile(int n, int r)
{
tableSize = n;
bucketSize = r;
/******************* initialize table assist *********/
tableAssist = new int[tableSize];
for (int j = 0; j < tableSize; j++)
{
tableAssist[j] = 0;
}
/**** create Table size * bucket size blank entries ****/
DataRec tempDataRec;
tempDataRec.id = 0;
ofstream outfile("Bout", ios::out);
for (int i = 0; i < tableSize * bucketSize; i++)
{
outfile.seekp( i * sizeof(DataRec) );
outfile.write( (char *) &tempDataRec, sizeof(DataRec) );
}
outfile.close();
}
int HashFile::store(const DataRec &data_rec)
{
ofstream outfile;
outfile.open("Bout", ios::out);
int temp = h(data_rec.id);
if (tableAssist[temp] == 0)
{
outfile.seekp( temp * sizeof(DataRec) );
outfile.write( (char *) &data_rec, sizeof(DataRec) );
tableAssist[temp]++;
return 0;
}
if (tableAssist[temp] == 1)
{
outfile.seekp( (temp+1) * sizeof(DataRec) );
outfile.write( (char *) &data_rec, sizeof(DataRec) );
tableAssist[temp]++;
return 0;
}
if (tableAssist[temp] == 2) //h2 - double hash
{
temp = h2(data_rec.id);
}
/*
*/
return -1;
}
int HashFile::h(int k)
{
return (k % tableSize);
}
int HashFile::h2(int k)
{
return (k % (tableSize - 1) + 1);
}
main.cpp
Code:
#include <iostream>
#include "func.h"
using namespace std;
int main()
{
DataRec temp;
temp.id = 1;
HashFile hashobj(7, 2);
return 0;
}
func.h
Code:
#ifndef FUNC_H
#define FUNC_H
#include <fstream>
//using namespace std;
struct DataRec
{
int id;
char name[20];
};
class HashFile
{
public:
HashFile(int, int);
int h(int);
int h2(int);
int store(const DataRec&);
int retrieve(DataRec&);
private:
int tableSize;
int bucketSize;
int * tableAssist;
};
#endif