Search code examples
cstrtok

Why does strtok() make my program return negative value?


I have a program in which I want to read text from a file and then store it in an array of structures. I tried to do it with strtok(). Here's code:

#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;
}

Here's text file:

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

There are more of them but I've shortend it a little and there is an empty line at the end.

Here's an output:

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

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

As you see, my program doesn't return max_tab after while loop and I don't know why.

@edit:

Added full code.


Solution

  • Here:

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

    get rid of EOF.

    Then probably you understand that this if(line) is not needed, as it's always evaluated to true.