将文本文件读入哈希表

时间:2018-06-24 16:32:43

标签: c io binary hashtable read-write

我有一个hashTable,我一直在尝试从文本文件中读取密钥/数据对。当我阅读它时,它似乎已被正确阅读,但是当我打印内容时,仅在表的每个索引处打印文本文件中的最后一个条目。这是我的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:Insta alsdhfishInsta

//这是我的主输出 索引1:Insta alsdhfish 索引2:Insta AlsdhfishInsta 索引3:Insta alsdhfishInsta

//这是我删除hashTable时main的结尾 //它停在2并给我一个malloc错误 完成删除索引1(共5) 完成删除索引2的5

0 个答案:

没有答案