[Solved] What is wrong with my code? C language [closed]


There are several errors in your code, for example strings that are too short, use of feof() and trying to use fgets() several times on the same text line in the file. While possible, it’s not very clean, so I’ve use strtok() after reading a whole text line.

In this re-written code I have also detected when the month changes. I’ve used pointers to the data within the line. Please note that if you want to store the extracted data into arrays, you’ll have to make such arrays and copy the data, because the data is overwritten on every line.

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

int main(int argc, const char * argv[])
{
    FILE *fr;
    char line[42];
    char *date, *pack, *method;
    int year, month, day, lastmonth = -1;

    if((fr = fopen("input.txt","r")) == NULL)
        exit(1);

    while(fgets(line, sizeof line, fr) != NULL) {   // instead of feof()

        pack = method = NULL;                       // preset to test later
        date = strtok(line, " \r\n\t");             // strip newline too
        if(date && strlen(date) == 10) {            // check valid substring
            year  = atoi(date);
            month = atoi(date+5);
            day   = atoi(date+8);
            printf("%04d-%02d-%02d", year, month, day);
            pack  = strtok(NULL, " \r\n\t");
            if(pack) {                              // was substring extracted?
                method  = strtok(NULL, " \r\n\t");
            }
            if (pack && method) {                   // were substrings extracted?
                printf(" %s %s", pack, method);
                if (month != lastmonth && lastmonth >= 0)
                    printf(" *New month*");
                }
            else {
                printf(" *Ignored*");
            }
            lastmonth = month;
            printf("\n");
        }
        else {
            printf("*Invalid line*\n");
        }
    }

    fclose(fr);
    return 0;
}

Program output:

2015-05-01 A GG
2015-05-02 H GG
2015-05-03 H AA
2015-05-05 G SS
2015-05-06 D GG
2015-05-17 V GG
2015-05-24 *Ignored*
2015-05-29 V GG
2015-06-01 V GG *New month*

1

solved What is wrong with my code? C language [closed]