Jake Cooper
Jake Cooper

Reputation: 109

Extra Line read from file

I'm trying to read from a text file and store it into an array, but my last array is filled with garbage, is there any way to fix it? For reference, I don't need that last line of values, but I can't seem to find a way to get rid of it.

int k;
char string[100];
for(k = 0; k < MAX_STATIONS; k++){
    if (fgets(string, sizeof(string), fp) == 0){
        break;
    }
    fscanf(fp,"%d %f %d %d %d %d %d %f %f", &stationInfo[k].stationID, &stationInfo[k].temperature, &stationInfo[k].year, &stationInfo[k].month, &stationInfo[k].day, &stationInfo[k].hour, &stationInfo[k].minute, &stationInfo[k].location.latitude, &stationInfo[k].location.longitude);
    printf("%d %1.2f %d %d %d %d %d %f %f\n", stationInfo[k].stationID, stationInfo[k].temperature, stationInfo[k].year, stationInfo[k].month, stationInfo[k].day, stationInfo[k].hour, stationInfo[k].minute, stationInfo[k].location.latitude, stationInfo[k].location.longitude);
}

EDIT: I've realized that using this method, I don't actually get the first line of my file read. How could I fix this?

Upvotes: 1

Views: 85

Answers (1)

stacker
stacker

Reputation: 68942

You should check the return value of fscanf it returns the number of read fields and ignore (or print a warning) lines which are incomplete. Another idea would be to check whether 100 chars are really long enough to hold the longest line (+ EOS).

Upvotes: 2

Related Questions