c - 为什么 strtok() 使我的程序返回负值?

标签 c strtok

我有一个程序,我想从文件中读取文本,然后将其存储在结构数组中。我尝试用 strtok() 来做到这一点。代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct kon {
    char name[50];
    int year;
    char city[50];
};
typedef struct kon kon;

int main(void) {
    FILE *input;
    input = fopen("kon.txt", "r");

    if (!input) {
        printf("No such file");
    }
    else {
        kon *tab;
        char line[256], year_tmp[10], *token;
        int counter = 0, max_tab = 2, year;

        tab = (kon*)malloc(max_tab * sizeof(kon));

        while(fgets(line, sizeof(line), input) != EOF) {
            if(line) {
                token = strtok(line, ", ");

                strcpy(tab[counter].name, token);
                token = strtok(NULL, ", ");

                strcpy(year_tmp, token);
                year = atoi(year_tmp);
                tab[counter].year = year;
                token = strtok(NULL, ", ");

                strcpy(tab[counter].city, token);

                printf("%s, %d, ", tab[counter].name, tab[counter].year);
                printf("%s\n", tab[counter].city);

                counter++;
            }

            /* Reallocing memory for array if needed */
            if(counter == max_tab - 1) {
                max_tab += 2;
                tab = realloc(tab, max_tab * sizeof(kon));
            }

        }
        printf("%d", max_tab);
        free(tab);
        fclose(input);
    }
    return 0;
}

这是文本文件:

RUMIANEK, 1998, Warsaw,
ALAMOS, 1991, Madrid,
BOSSIER, 2004, Paris,

还有更多,但我把它缩短了一点,最后有一个空行。

这是一个输出:

RUMIANEK, 1998, Warsaw
ALAMOS, 1991, Madrid
BOSSIER, 2004, Paris

Process returned -1073741819 (0xC0000005)   execution time : 2.122 s
Press any key to continue.

如您所见,我的程序在 while 循环后不返回 max_tab,我不知道为什么。

@编辑:

添加了完整代码。

最佳答案

这里:

while(fgets(line, sizeof(line), input) != EOF)

摆脱 EOF。

那么您可能会明白这个 if(line) 是不需要的,因为它总是被评估为 true。

关于c - 为什么 strtok() 使我的程序返回负值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50773670/

相关文章:

c - 琴弦不能正常工作

c - 只需要写一个大文件就需要 O_LARGEFILE 吗?

c++ - 我可以 Hook "Ctrl+Alt+Del"的返回值吗?

c - 如何在 for 循环中使用 strtok()?

c - 在 C 中将 char 指针分配给 char 数组

C strtok 没有标记空标记值

c - C中的strtok和strsep有什么区别

c - 在 C 中使用位运算符获取位值

c - 为什么这个程序中printf的用法是错误的?

将 Char * 缓冲区转换为十六进制以便在 c 中打印