首页 > 解决方案 > 读取文件到链表 C

问题描述

大家好,我正在尝试将文件加载到链表,然后将其打印到 2 个数组。我不知道我的代码有什么问题,我不知道如何处理 2 个数组,当我将它打印为字符串时它可以工作,但对于两个数组它不起作用。我是 c 编程的新手,我的代码:

    struct list {
    char *string1;
    struct list *next;
};

    typedef struct list LIST;



 int read_file(char * filename)
int a[20], b[20];
FILE *fp;
char line[128];
LIST *current, *head;
head = current = NULL;
int i = 0;
fopen_s(&fp, filename, "r");
if (fp == NULL) {
    printf("ERROR");
    return 0;
}
while (fgets(line, sizeof(line), fp)) {
    LIST *node = malloc(sizeof(LIST));
    node->string1 = strdup(line);
    node->next = NULL;
    char str[20];
    char* field = strtok(line, ",");
    strcpy(str, field);
    a[i] = (int)atof(str);
    field = strtok(NULL, ",");
    b[i] = (int)atof(field);
    i++;
    printf("%4d\t%4d\n", a[i],b[i]);
    if (head == NULL) {
        current = head = node;
    }
    else {
        current = current->next = node;


    }
}
fclose(fp);

标签: cfilelinked-list

解决方案


推荐阅读