У меня есть хэш-таблица, и я пытался прочитать пары ключ / данные в нее из текстового файла. Когда я читаю его, кажется, что он был прочитан правильно, но когда я печатаю содержимое, только последняя запись в текстовом файле печатается в каждом индексе таблицы. Вот мои функции readFile, saveFile:
int readFile(char * fileName, HTable * hashTable){
char *key = malloc(sizeof(char*));
char *data = malloc(sizeof(char*));
int eof;
//char buf[50];
//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 0;
}
//Set a temp Node to hold data, read data into the temp Node
//and insert temp into hashtable
printf("Here we go\n");
while(1){
eof = fscanf(fp, "%s %s", key, data);
if(EOF == eof)
break;
//fgets(buf, 50, fp);
//sscanf(buf, "%s %s", key, data);
insertData(hashTable, key, data);
printf("Index %d: %s %s\n\n", hashTable->hashFunction(hashTable-
>size, key), key, data);
}
//Close file pointer
fclose(fp);
return 1;
}
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){
fprintf(fp, "%s %s \n", temp->key, temp->data);
temp = temp->next;
printf("saved....\n");
}
printf("Index %d saved\n", i);
}
//Close file pointer
fclose(fp);
}
И мой вывод при попытке прочитать файл:
// Это вывод файла readFile, сообщающий, куда делись данные
Индекс: 1
Индекс 1: Facebook sjfl253sFace
Индекс: 2
Индекс 2: Gmail 343728Gamil
Индекс: 3
Индекс 3: Инста alsdhfishInsta
// Это вывод из моего основного
Индекс 1: Инста alsdhfishInsta
Индекс 2: Инста alsdhfishInsta
Индекс 3: Инста alsdhfishInsta
// Это конец main, когда я удаляю hashTable
// останавливается на 2 и выдает ошибку malloc
Завершено удаление индекса 1 из 5
Завершено удаление индекса 2 из 5