2014-05-24 32 views
-3

我正在做一个程序来保存文件结构中的联系人列表。我尝试了很多东西,但是当我尝试去阅读文件到程序中时,它不会读取任何内容。将结构保存在一个文件中

这是我没有打开文件并保存到文件的程序:

#include <stdio.h> 
#include <stdlib.h> 

struct agenda { 
    int idContacte; 
    char name[50]; 
    struct agenda *nextContacte; 
}; 
struct agenda *pAgenda; 
struct agenda *pFirst = NULL; 
struct agenda *pIndex; 

void insert(); 
void show(); 

int main() 
{ 
    //Menu 
    int opc; 
    while(1){ 
     printf("1.Insert Contact.\n"); 
     printf("2.Show Contacts.\n"); 
     printf("3.Exit\n"); 
     scanf("%d", &opc); 
     switch(opc){ 
      case 1: 
       insert(); 
       break; 
      case 2: 
       show(); 
       break; 
      case 3: 
       return 0; 
     } 
    } 
} 
void insert(){ 
    pAgenda = (struct agenda *)malloc(sizeof(struct agenda)); 
    printf("Insert ID: "); 
    scanf("%d", &pAgenda->idContacte); 
    printf("Insert the name: "); 
    scanf("%s", pAgenda->name); 
    printf("\n"); 
    if (pFirst==NULL || pAgenda->idContacte < pFirst->idContacte) 
    { 
     pAgenda->nextContacte=pFirst; 
     pFirst=pAgenda; 
    } 
    else if (pAgenda->idContacte > pFirst->idContacte){ 
     pIndex=pFirst; 
     while(pIndex->nextContacte && pIndex->nextContacte->idContacte < pAgenda->idContacte) 
     { 
      pIndex = pIndex->nextContacte; 
     } 
     pAgenda->nextContacte = pIndex->nextContacte; 
     pIndex->nextContacte = pAgenda; 
    } 
} 
void show(){ 
    pIndex = pFirst; 
    while(pIndex && pIndex->idContacte <= 100) { 
     printf("\nID: %d", pIndex->idContacte); 
     printf("\nNAME: %s", pIndex->name); 
     printf("\n\n"); 
     pIndex = pIndex->nextContacte; 
    } 
} 

你能帮助我,我怎样才能从文件在程序开始接触,然后在插入接触,改写文件并再次将所有联系人插入文件中?

+0

没有代码读取开始??? – alk

回答

2

当你结束你的程序,你应该做以下

int save_list(struct agenda *head) { 
    FILE *save = fopen("file.name", "wb"); 
    if(!save) return -1; 

    while(head) { 
    fwrite(head, sizeof *head - sizeof head, 1, save); 
    head = head->nextContacte; 
    } 

    fclose(save); 
    /* Somebody would free list memory after this function execution */ 
    return 0; 
} 

在你的程序,你应该做以下

struct agenda *restore_list() { 
    FILE *restore= fopen("file.name", "rb"); 
    struct agenda *head = NULL; 
    struct agenda *cur = head; 
    struct agenda temp; 
    if(!restore) return head; 

    while(fwrite(&temp, sizeof temp - sizeof head, 1, save) == 1) { 
    struct agenda *node = malloc(sizeof(struct agenda)); 
    if(NULL == node) { 
     /* Handle out of memory error here, free list */ 
     return NULL; 
    } 
    *node = temp; 
    node->nextContacte = NULL; 
    if(head) { 
     cur->nextContacte = node; 
     cur = node; 
    } else { 
     /* First node */ 
     head = cur = node; 
    } 
    } 

    fclose(restore); 
    return head; 
} 
+0

也许你的意思是'struct agenda * restore_list(){'。而'fread'而不是'fwrite'在同一个函数中。 –

+0

@RSahu谢谢。接得好。我会根据你的建议更新。 –

+0

干得好。你被Raxkin聘用了。 – harper

相关问题