연결된 목록을 사용하여 사전을 구현하는 C 코드를 작성했습니다 (노드가 정렬 된 순서로 있음). 데이터를 파일에 저장하고 다음에 프로그램을 실행할 때 데이터를 다시로드 할 수 있기를 원합니다. 파일에서 데이터를로드하는 데 문제가 있습니다. 데이터를 읽고 쓰는 코드는 다음과 같습니다.
struct node{
char word[20];
char meaning[5][100]; //2D array for saving multiple meanings of a word
struct node *next;
};
void ReadData(struct node *head)
{
struct node *tail;
FILE *fp = fopen("dictionary.data", "rb");
if(fp == NULL)
{
printf("Error opening file..\n");
return;
}
while(!feof(fp))
{
tail = (struct node*)calloc(1, sizeof(struct node));
fread(tail->word, sizeof(head->word), 1, fp);
fread(tail->meaning, sizeof(head->meaning), 1, fp);
if(head == NULL) //for fresh run head is initialized with NULL
{
tail->next = head;
head = tail;
}
else
{
head->next = tail;
head = head->next;
}
}
fclose(fp);
}
파일에서 연결된 목록으로 데이터를로드 할 수 없습니다. 코드가 작동하지 않습니다. 문제가 어디에 있는지 알아낼 수 없습니다 ..
파일에 데이터를 쓰는 방법 은 다음과 같습니다.
/*I think this code is working because size of the file increases after running the code*/
void WriteData(struct node *head)
{
FILE *fp = fopen("dictionary.data", "wb");
if(fp == NULL)
{
printf("Error opening file..\n");
return;
}
while(head != NULL)
{
fwrite(head->word, sizeof(head->word), 1, fp);
fwrite(head->meaning, sizeof(head->meaning), 1, fp);
head = head->next;
}
fclose(fp);
}
sizeof
대신을 사용 strlen
했습니다. 문자열입니다. 끝에는 null 문자가 있습니다. 문자열에는 문제가 없습니다. 그래도 더 많은 메모리를 소비합니다.
이것을 시도하십시오 (예상되지 않음) :
void ReadData(struct node **head){//or struct node *ReadData(void){ ... return head; }
struct node temp = { .next = NULL };//{ {0}, {{0}}, NULL}
struct node *hp, *curr;
FILE *fp = fopen("dictionary.data", "rb");
if(fp == NULL){
printf("Error opening file..\n");
return;
}
hp = *head;
while(fread(temp.word, sizeof(temp.word), 1, fp) && fread(temp.meaning, sizeof(temp.meaning), 1, fp)){
struct node *np = malloc(sizeof(*np));
if(np == NULL){
perror("couldn't make new node by malloc:");
return ;//release list
}
*np = temp;
if(hp == NULL){//for fresh run head is initialized with NULL
curr = hp = np;
} else {//If *head isn't NULL, you need to move to the last node first.
curr = curr->next = np;
}
}
fclose(fp);
*head = hp;
}
//....................
int main(void){
//...
struct node *head = NULL;
//...
ReadData(&head);
//...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다