从txt文件读取链接列表

用户名

好的,所以我被告知要从文件中读取列表,我已经以某种方式将文件中的数据分开,建议使用strtok。似乎我正在读取正确的数据,但是如何将这些数据传递给我的AddAddClient函数?

文件中的数据如下所示:

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;
}
}
累了的蛋糕

我读到您的问题是如何
从行中提取名字/姓氏(例如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;
}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章