Read text file picking float numbers and playing in array

0

I have a text file for example with:

v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000

The expected output is an 8x3 float array (in this case), since the array will always have the same number of rows as the file, with the respective values of each row,

[0][1] =  1.000000
[0][2] = -1.000000
[0][3] = -1.000000

[1][1] =  1.000000
[1][2] = -1.000000
[1][3] =  1.000000
.
.
.

As long as I do not move with C, I ended up forgetting a lot of things and my attempts were not even close to expected, I can only read character by character of the line and identify when the line break. Can anyone help solve this problem by getting 3 floats per line?

Last attempt was to count the number of lines, gave keto, but from there I did not find how to get the 3 floats of the line:

void readOBJ(char *file)
{
    char ch;
    int lines = 0;

    FILE *arq;
    arq = fopen(file, "r");
    if(arq == NULL)
            printf("Erro, nao foi possivel abrir o arquivo\n");
    else {
        do {
            ch = fgetc(arq);
            if(ch == '\n')
                lines ++;
        }while(ch != EOF);
    }

    fclose(arq);
}
    
asked by anonymous 09.11.2016 / 04:23

1 answer

1

fscanf has an intelligent formatting system. If the lines you need to read follow this pattern (starting with v and followed by 3 floats), then you can do something like:

fscanf(arq, " v %f %f %f", &v[i][0], &v[i][1], &v[i][2]);

To know when to stop (end of file), use the return value of fscanf : the function returns a positive value if it can read something, and EOF if it is over.

    
09.11.2016 / 04:43