Read text file picking float numbers and playing in matrix

Asked

Viewed 877 times

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 matrix (in this case), because the matrix will always have the same number of lines as the file, with the respective values of each line, be:

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

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

Since I haven’t been dealing with C for a long time, I’ve forgotten a lot of things and my attempts have not been nearly as expected, I can only read character by character of the line and identify when the line breaks. Can anyone help solve this problem, of catching 3 floats per line?

Last attempt was to count the number of lines, that’s right, but from there I found no way to catch 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);
}

1 answer

1


The fscanf has a smart 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 the end has come.

  • 1

    I got it here, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.