I'm trying to analyze a file, given with a structure like this:
Key1 param1 param2 param3
Key2 param4 param5 param6 param7
Key3 param8 param9
The file has unknown number of lines, each line begins with a key and has unknown amount of parameters.
I want to compare one key's parameter with another key's parameter, the one's in the same column respectively, to be exact (in the example above, these would be param1 and param4, or param2 and param5 and so on).
I started by opening the file and looping through all the lines, like this:
Code:
char row[30];
while (fscanf(fp, "%s\n", &row) == 1)
{
...
}
But I already don't like that I'm defining a fixed array as I'll be screwed if the row's length is greater that 30.
Ignoring that, inside the loop, I tried to split the row into parts (using strtok), to get the keys and parameters. I did it like that:
Code:
typedef struct
{
char *name;
char params[20][6];
int n;
} rows;
void splitrows(const char *row, rows *frows)
{
int i = 0;
char *tbc = " "; // Horizontal tab character
char *frow = malloc(sizeof *row);
frow = strdup(row);
char params[10][20];
char *t = strtok(frow, tbc); (*frows).name = t;
while (t != NULL)
{
strcpy((*frows).params[i++], t);
t = strtok(NULL, tbc);
(*frows).n = i;
}
free(frow);
}
I would then call the function out in the while loop and load up an array of rows (the structure 'rows') and then do the math and everything else i really need to do. Like this:
Code:
char row[30]; int rnr = 0, i = 0;
while (fscanf(fp, "%s\n", &row) == 1) rnr++; // Get the number of lines in the file
rows frows[rnr]; // Make an array of rows.
while (fscanf(fp, "%s\n", &row) == 1)
{
splitrows(row, &frows[i]); i++;
}
But unfortunately it doesn't work. And it's really messy. I'm using fixed size array's where I shouldn't (as I don't have a glue how to do it otherwise).
Is there another way to do this ? Could anyone please at least point me in the right direction ?
Best wishes and many thanks,
Desmond