I am trying to implement linear probing for collision resolution for a hash table in C. I am inserting and retrieving the information from a file using the RRN (record relative number) to locate the index where each register will be inserted/retrieved. Initially, I am setting all the index values to "_" as a way to mark them as empty. So far, so good. The bump I have come across is when I actually attempt to implement the collision resolution. The program seems to be overwriting the record that was there instead of looking for the next available spot. Also, when I purposefully look for a record with a non-existent key (name), the program gets stuck.
I am setting the pointer back to the beginning of the file whenever fd=0 (when it reaches the end of the file, in other words), but something tells me this might be the problem. Can you guys take a look? Thanks in advance:
//Simplified data struct that will be used
struct client{
char last_name[15];
char maiden_name[15];
char name[15];
}client
//Hash function
int Hash(char nm[15]){
int key, sum = 0, i;
//Sums the ASCII values of each letter in the client's name
for (i=0;nm[i]!='\0';i++){
sum=sum+nm[i];
}
key=sum%10; // Divides the sum by 10 and saves the modulus value in key variable
return key;
}
I am omitting some code for clarity's sake, but this is where I implement a while loop to verify whether a register is empty:
key= Hash(buff.name); // Uses Hash function to get key (index) value of where record will be stored
beginning=key;
lseek(fd, sizeof(client) * key, SEEK_SET); // Moves pointer to insert location
read(fd, &read_buf, sizeof (client)); // Reads the record contents in memory
while((strcmp("_",read.name)) != 0){ // While record is not empty...
++key; //Increase the key value
lseek(fd, sizeof (client) * key,SEEK_SET); // Change pointer to new location
read(fd, &read_buf, sizeof (client)); // Read contents into memory again
if (fd==0){ //If file descriptor reaches end of file, set key back to the beginning
key=0;
}
if (key== beginning){ // If key reaches the origin location of the search, print out error and exit
printf("There are no more spaces in the file!");
break;
}
}
write(fd, &buff, sizeof client);
printf("The record has been inserted successfully!\n");