I have a function that is trying to read each line of a file, then use sscanf to pass values into an array of structs, creating a new struct for each line of the file that is not a comment line containing char '#'. This is my code:
typedef struct {
int row, col, C, D;
char program[80];
} agentDetails;
My structs are defined in a header file, #included in the main file.
char currentLine[80];
char** agents;
int n=0;
agents = malloc(sizeof(char*)*4);
while (fgets(currentLine, sizeof currentLine, file) != NULL) {
if(!strchr(currentLine, '#')) {
agentDetails agents[n]; /*create new struct in array agents*/
sscanf(currentLine, "%d %d %c %s %s", &agents[n].row, &agents[n].col, &agents[n].C, agents[n].program, agents[n].D);
n++;
}
}
this works, however when it reaches end of file it does not exit the loop, it sits there waiting for input. I have tried stepping through with gdb, after the last line it steps to the while(fgets...) line, and then waits for input.
I know this code works if I try to sscanf values into variables initialised within the function, it only seems to fault when I use an array of structs. What is happening here?
I have changed the code so it works, see below:
int n = 0;
int i = 0;
while (fgets(currentLine, sizeof currentLine, file) != NULL) {
if(!strchr(currentLine, '#')) {
n++;
}
}
rewind(file);
agentDetails agents[n];
while (fgets(currentLine, sizeof currentLine, file) != NULL) {
if(!strchr(currentLine, '#')) {
sscanf("same as above");
i++;
}
}
I dont use malloc, however. Is this a problem? Will this cause issues?
currentLineis declared ? - phoxis&agents[n].C agents[n].programinsscanf? - phoxis