Alvaro Carvajal Nakosmai Alvaro Carvajal Nakosmai - 18 days ago 7
C Question

C Read from file to populate linked list

I have a txt file that I need to read and populate a linked list. The file structure is the following

IBE0101;2016;11;20;07;50;Alvaro;Carvajal;12345678R
IBE0101;2016;11;20;07;50;Juan;Garcia;12345678R


I am trying to read it doing the following

tPassenger * ops_loadPassengersList()
{
tPassenger * retValue;

retValue = malloc(sizeof(tPassenger));

tPassenger *lastPassenger = retValue;

// Open file handle with read mode
FILE *file = fopen(OPS_PASSENGERS_FILE, "r");

// Loop until end of file
while(!feof(file)) {
tDateTime date;
fscanf(file, "%[^;];%d;%d;%d;%d;%d;%[^;];%[^;];%[^;]\n", lastPassenger->name, &date.year, &date.month, &date.day, &date.hour, &date.minute, lastPassenger->name, lastPassenger->surname, lastPassenger->dni);
printf(lastPassenger->name);
if(!feof(file)) {
lastPassenger->nextPassenger = malloc(sizeof(tPassenger));
lastPassenger = lastPassenger->nextPassenger;
}
}


// Close file handle
fclose(file);

return retValue;
}


However I get stuck on a infinite loop by fscanf not finding what I told to scan on? The pattern seems correct the first iteration works fine.

The tDateTime element is not used on this piece but I want to get it too.

Answer

Probably you should not parse the line yourself. There is a strtok() function which can give you the tokens separated by a delimiter. But this will not give you all the feilds together in one call. You will need to call it as many times as the number of fields are in a line of the file.

Similar method is discussed here

Comments