2014-01-23 29 views
1

好了,所以我已被告知,從文件我不知怎麼分開,我一直recomended使用strtok的文件數據讀取我的名單,看來我讀正確的數據,但我該怎麼辦將這些傳遞給我的添加AddClient函數?讀數鏈表從txt文件

數據文件看起來是這樣的:

Client: Adrian Kulesza 
Item: przedmiot cos 123.000000 cosu 1234.000000 1 2 3 

Client: Bartosz Siemienczuk 

頁眉:

struct date 
    { 
     int day; 
     int month; 
     int year; 
     struct date* next; 
    }; 
    struct item 
    { 
     char item_name[30]; 
     char item_state[30]; 
     float item_price; 
     char item_status[30]; 
     float item_price_if_not; 
     struct date *issue_date; 
     struct item *next; 
    }; 
    struct client 
    { 
     char client_name[30]; 
     char client_last_name[30]; 
     struct item *item_data; 
     struct client *next; 
    }; 

代碼:

void ReadList(struct client *head) 
{ 
    int i=0,b=0; 
    char line[126]; 
    FILE* fp = fopen("data.txt","r"); 
    if (fp == NULL) 
    { 
    puts("Can't open the file"); 
    return 1; 
    } 
    while(fgets(line, sizeof(line), fp) != NULL) 
    { 
    char* token = strtok(line, " "); 
    if(strcmp(token,"Client:") == 0) 
    { 
     while (token != NULL) 
     { 
     puts(token); 
     token = strtok(NULL, " "); 
     } 
    } 

    else 
     if(strcmp(token,"Item:") == 0) 
     { 
     while(token != NULL) 
     { 
      puts(token); 
      token = strtok(NULL, " "); 
     } 
     } 
    } 

void AddClient(struct client **head, char name[30], char last_name[30]) 
{ 
    if((*head) == NULL) 
    { 
     *head = malloc(sizeof(struct client)); 
     strcpy((*head)->client_name,name); 
     strcpy((*head)->client_last_name,last_name); 
     (*head)->next = NULL; 
     (*head)->item_data = NULL; 
    } 
    else 
{ 
    struct client *temp; 
    temp = (*head); 
    //    // 
    while(temp->next) 
    temp=temp->next; 
    //    // 
    (temp->next) = malloc(sizeof(struct client)); 
    strcpy(temp->next->client_name,name); 
    strcpy(temp->next->client_last_name,last_name); 
    temp->next->next = NULL; 
    temp->next->item_data = NULL; 
} 
} 
+0

你寫的函數,但不知道在哪裏調用它?這就是weirld ...每次讀完一個節點的所有數據之後。 – moeCake

+0

不,我知道如何用普通的數據輸入來調用它是否有可能以某種方式將我的函數添加到readlist中?我不知道如何使用strtok的,我想在這裏從保存到文件 – user3209183

+0

如果你覺得列表重新鏈接我的名單張貼至少從輸入文件樣本數據爲兩種情況你佔('客戶: '和'Item:')會很有幫助,你說得對。如果它的編碼適當,你的'AddClient'不需要特殊情況下的NULL指針。按照書面的說法,你在聲明爲void的函數中返回1,缺少關於ReadList的關閉對象,沒有示例數據,也沒有'main()'說。 – WhozCraig

回答

0

,我讀了你的問題是如何提取/姓(例如Adrian Kulesza)
,並將它們傳遞給ReadList()。

這裏是快速和骯髒的測試代碼簡化後您的問題:

int main(void) 
{ 
    char line[126] = "Client: Adrian Kulesza"; 
    char name[30], last_name[30]; 

    char* token = strtok(line, " "); 
    if(strcmp(token,"Client:") == 0) 
    { 
     token = strtok(NULL, " "); 
     strcpy(name, token); 

     token = strtok(NULL, " "); 
     strcpy(last_name, token); 
    } 

    printf("%s %s\n", name, last_name); 

    return 0; 
} 

現在你得到的名字和姓氏,他們進入了addClient(),
但是你可能需要的錯誤處理,也是項目部分。