c - 从txt文件中读取链表

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

最佳答案

我了解到您的问题是如何提取名字/姓氏(例如 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(),
但您可能需要错误处理以及项目部分。

关于c - 从txt文件中读取链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21300063/

相关文章:

c - 如何解决这个linux定时器错误

c++ - 对于卷句柄,来自 FILE_END 的 SetFilePointer 始终失败

c++ - 如何一次从文件中读取两个十六进制值

c - 用文件 txt 中的单词填充字符串数组

java - Java中第三方库文件句柄泄漏的检测和处理

c - 链表初始化

c - 在循环中使用 scanf 处理 SIGINT

c - 我在哪里可以下载 gd.h?

java - 用 Java 为我自己的 LinkedList 类编写自己的 peek() 方法

c++ - 链表 C++ 中的复制构造函数