I have a function in my code that reads some file line by line and creates structures from them. A professor said to me that there can be a problem and mentioned phantom line. Can someone see my function and explain me where is the problem?
This is my code:
void readComponentList(ComponentList *cl, char *fileName)
{
FILE *file = fopen(fileName, "r");
if (file == NULL) { perror(fileName); exit(1); } // If the file doesn't exist, the program termitates with exit code 1
int r;
Component *c = newComponent(cl);
// Creates useful component c by inserting line informations as arguments in the structure
r = fscanf(file, "%24s %24s %24s %d %lf", c->type, c->model, c->unit, &(c->weight), &(c->price));
while (r != EOF) // Doing the same thing for the rest of the lines
{
c = newComponent(cl);
r = fscanf(file, "%24s %24s %24s %d %lf", c->type, c->model, c->unit, &(c->weight), &(c->price);
// Since EOF only occurs after an unsuccessful read attempt, an additional "phantom line" with undefined content is read in here, which could lead to crashes.
}
fclose(file);
}
This is the file example that I am reading:
Motor M5x40 Stk 5 0.05
Elevator M5x60 Stk 6 0.05
ACM L-H-100 Stk 1250 530
SSM L-100 Stk 0 0
ElevatorW W3 Stk 0 0
Metal- kg 1000 344200
Component and ComponentList structures:
typedef struct
{
char type[25];
char model[25];
char unit[25];
int weight;
double price;
StepList *construction_steps;
} Component;
typedef struct
{
Component **components;
int count;
int allocated;
} ComponentList;