So I am creating a password vault and need to be able to save a HashTable to a binary file and read those same contents from the binary file back into the programs HashTable upon login
I have been playing around with fwrite and fread for a solid 4 hours and cannot seem to find where i am going wrong. Currently i am segfaulting, i have tried GDB to find it but just get the message:
Thread 2 received signal SIGSEGV, Segmentation fault.
0x00007fff9a9a16a0 in ?? ()
My code for reading in a file is:
void readFile(char * fileName, HTable * hashTable){
//Create file pointer and point it at fild to open
FILE * fp;
fp = fopen(fileName, "rb+");
//check if file exists
if(!fp){
printf("File could not be opened\n");
return;
}
//Set a temp Node to hold data, read data into the temp Node
//and insert temp into hashtable
Node * temp;
while(1){
fread(&temp, sizeof(Node), 1, fp);
insertData(hashTable, temp->key, temp->data);
if(feof(fp) != 0)
break;
printf("is this working?\n");
}
//Close file pointer
fclose(fp);
}
and my code for writing to the file is:
void saveFile(char * fileName, HTable * hashTable){
//Create a FILE pointer and point it to the file to open or create
FILE * fp;
fp = fopen(fileName, "wb+");
//If the file does not exist or cannot be created give error message
if(!fp){
printf("ERROR: File could not be created\n");
return;
}
//for each index of the hashTable write its contents to the file
for(int i = 0; i < hashTable->size; i++){
Node * temp = hashTable->table[i];
while(temp != NULL){
fwrite(&temp, sizeof(Node), 1, fp);
temp = temp->next;
printf("saved....\n");
}
printf("Index %d saved\n", i);
}
//Close file pointer
fclose(fp);
}
I know the segfault isnt coming from the insertData function as i have tested that and know it works properly. My best guess for what I am doing wrong is that something about my fwrite conditions are not right or that when I am reading the data I am mis managing memory somewhere.
also the HashTable struct is:
typedef struct HTable
{
size_t size;
Node **table;
void (*destroyData)(void *data);
int (*hashFunction)(size_t tableSize, char * key);
void (*printData)(void *toBePrinted);
}HTable;
and my Node struck is:
typedef struct Node
{
char * key;
void *data;
struct Node *next;
} Node;
Thank you for any feedback!!