Search code examples
cfileloopstokenfgets

fgets and strtok in a double "for" loop


I'm trying to extract the content of a file into a matrix but the file may look completely differently.

For exemple all these files should give the same result : a 3x3 matrix containing 1,2,3,4,5,6,7,8,9.


1 2 3 
4 5 6
7 8 9

1  2  3 
4 5 6
7         8 9

1 2 3 4
5
6
7   8 
9

1 2 3
$something
$something else
4 5 6
$something else else
7 8 9

Hopefully I know the dimensions of the matrix beforehand as well as the "$" character that indicates that these lines are to be ignored in the current process.

My current algorithm using fscanf works great but It can't work with the "$something" lines.

I figured that I should use the fgets/strtok/sscanf method but there are some issues.

// File* file (already assigned)
char line[32]; //assuming 32 is enough
char* token;

fgets(line,32,file);
token = strtok(line," \t");

for (y=0; y<ySize; y++)
{
    for (x=0; x<xSize, x++)
    {
        if (token[0] == '$') //should use a str function
        {
            fgets(line,32,file);
            token = strtok(line," \t")
            x--;
        }
        else
        {
            if (we are at the end of the line)
            {
                fgets(line,32,file);
                token = strtok(line," \t")
            }
            sscanf(token,"%d",&matrix[x][y];
            token = strtok(NULL," \t");
        }
    }
}

Basically I'd like to have some help to write the "if (we are at the end of the line)" condition and some input on my method, is it flawless? Did I correctly thought of the process?

Thank you.


Solution

  • You should use getline instead of fgets to make things easier. The latter is unreliable. The test condition that you are looking for is:

    token == NULL;
    

    Check this: "Once the terminating null character of str has been found in a call to strtok, all subsequent calls to this function with a null pointer as the first argument return a null pointer."