Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Read until end of file

Tags:

c

I currently have code that reads 4 lines and I want to be able to change that until EOF or my MAX const int value. I can not get the !EOF to work right and was wondering how would I change my code to accomplish this?

Thanks in advance

#include <stdio.h>

struct record{
    char name[2];
    int arrival_time;
    int job_length;
    int job_priority;
};

const int MAX = 40;

int main(void)
{
    struct record jobs[MAX];
    int i = 0;
    int j;
    FILE *f = fopen("data.dat","rb");

    while (fscanf(f, "%s %d %d %d", &jobs[i].name, &jobs[i].arrival_time,
                  &jobs[i].job_length, &jobs[i].job_priority) == 4 && i < MAX)
      i++;

    for (j = 0; j < i; j++)
        printf("%s %d %d %d\n", jobs[j].name, jobs[j].arrival_time,
               jobs[j].job_length, jobs[j].job_priority);

    fclose(f);

    return(0);
}
like image 506
Intelwalk Avatar asked Dec 21 '22 07:12

Intelwalk


2 Answers

Something like

while (fscanf(f, "   %s   ", &etc) != EOF) {

}

Then use feof(f) to check if it was a fscanf error or actually EOF.

like image 150
Martin Beckett Avatar answered Jan 10 '23 07:01

Martin Beckett


Your code seems to do what you want, except:

char name[2];

Names will probably be longer than 1 character.

FILE *f = fopen("data.dat","rb");

You seem to be reading text ("r") file, not binary ("rb").

&jobs[i].name should be jobs[i].name

like image 33
Piotr Praszmo Avatar answered Jan 10 '23 09:01

Piotr Praszmo