C - 复制到结构只返回文件

时间:2018-01-04 21:58:28

标签: c

我试图将每一行切割成子串,用斜杠分隔并将它们加载到结构列表中,但它所做的只是输入每行文件中的最后一个元素。

我的档案:

Adam Mickiewicz///Pan Tadeusz/Publisher 1/1833/24.99
Jules Verne///Around The World in 80 days/Publisher 1/1904/19.99
Jean-Jacques Sempe/Rene Goscinny//Little Nicholas/Publisher 2/1963/22.99

我的阅读算法:

struct element
{
    char *authors[AK];
    char *title;
    char *publisher;
    int year;
    float price;

    struct element *next;
};

typedef struct element Book;
char line[1024]; // Buffer
char *string; // Temporary string
char *found = "/";
Book *first = NULL; 
Book *current = NULL;

while (fgets(line, sizeof(line), fp)) {
    Book *new = malloc(sizeof(Book));
    string = strdup(line); // Duplicate each line in file
    // If encountered a separator, slice the line
    while ((found = strsep(&string, "/")) != NULL) {
        for (i = 0; i < AK; i++) {
            new->authors[i] = strdup(found);
        }
        new->title = strdup(found);
        new->publisher = strdup(found);
        new->year = atoi(strdup(found));
        new->price = atof(strdup(found));
    }
    if (first == NULL) {
        current = first = new;
    }
    else {
        current = current->next = new;
    }
}

输出:

Authors: 24.99
24.99
24.99
Title: 24.99
Publisher: 24.99
Year: 24
Price: 24.990000
=====================
Authors: 19.99
19.99
19.99
Title: 19.99
Publisher: 19.99
Year: 19
Price: 19.990000
=====================
Authors: 22.99
22.99
22.99
Title: 22.99
Publisher: 22.99
Year: 22
Price: 22.990000
=====================

很抱歉,如果之前发布了类似的内容。任何建议都会有所帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

你的循环:

while ((found = strsep(&string, "/")) != NULL) {
    for (i = 0; i < AK; i++) {
        new->authors[i] = strdup(found);
    }
    new->title = strdup(found);
    new->publisher = strdup(found);
    new->year = atoi(strdup(found));
    new->price = atof(strdup(found));
}

将行标记为最后一个字段(例如24.99)并设置/覆盖具有此值的所有字段(在此过程中存在大量内存泄漏)。

你不能使用循环,但是通过x调用strsep

一个接一个地提取每个标记

这是我(蹩脚,未经考验)尝试解决这个问题:

#define NEXT_TOKEN if ((found = strsep(&string, "/")) == NULL) return

     for (i = 0; i < AK; i++) {
       NEXT_TOKEN;
        new->authors[i] = strdup(found);
    }
    NEXT_TOKEN;
    new->title = strdup(found);
    NEXT_TOKEN;
    new->publisher = strdup(found);
    NEXT_TOKEN;
    new->year = atoi(found);
    NEXT_TOKEN;
    new->price = atof(found);

NEXT_TOKEN宏避免复制粘贴繁琐的strsep代码。

另外,请避免new,因为它是C ++关键字,只会使您的代码C兼容。