Alvaro Carvajal Nakosmai Alvaro Carvajal Nakosmai - 1 year ago 144
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


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.hour, &date.minute, lastPassenger->name, lastPassenger->surname, lastPassenger->dni);
if(!feof(file)) {
lastPassenger->nextPassenger = malloc(sizeof(tPassenger));
lastPassenger = lastPassenger->nextPassenger;

// Close file handle

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download