从txt文件中读取链表

时间:2014-01-23 05:25:34

标签: c file linked-list

好的,所以我被告知要从文件中读取我的列表我已经以某种方式将文件中的数据分开我已经建议使用strtok,看来我正在读取正确的数据但是如何将这些传递给我添加的AddClient功能

文件中的数据如下所示:

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;
}
}

1 个答案:

答案 0 :(得分:0)

我读到你的问题是如何提取名/姓(例如Adrian Kulesza)
从line,并将它们传递给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;
}

现在获取name和last_name,将它们传递给AddClient(),
但您可能需要错误处理以及项目部分。