Search code examples
cloopsfgetc

Weird loop while reading from a file in C


I'm writing a code in C to read matrixes (square matrix with 3 <= dim <= 9) from a .txt file and print it exactly how it is written. The file is arranged as follows:

5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX

The first number indicates the size of the subsequent matrix.

I wrote the following code:

int main () {
    FILE *arquivo;
    char A[9][9];
    int N;
    int i,j;
    char temp;
    arquivo = fopen("matrizes.txt", "r");
    if (!arquivo) printf("Erro.\n");
    while (fscanf(arquivo, "%d", &N) != EOF) {   
        printf("%d \n", N);
        fgetc(arquivo);
        for (i = 0; ((i < N) && (temp = fgetc(arquivo)) != '\n') ; i++) {
            for (j = 0; j < N; j++) {
                A[i][j] = temp;
            }
        }
        for (i = 0; i < N; i++) {
            for(j = 0; j<N; j++) {
                printf("%c", A[i][j]);
            }
            puts(" ");
        }
    }
    return 0;
}

The output is this

5 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
5 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
5 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
5 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
5 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
AAAAA 
6 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
6 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
6 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
6 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
6 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
6 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 
XXXXXX 

I honestly have no idea why this is happening. I tried different conditions to stop the loop, bot none of them worked out.

If I change

while (fscanf(arquivo, "%d", &N) != EOF)

into

while (fscanf(arquivo, "%d", &N) == 1)

the output is just

5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA

The value of the second loop scanf in this case is "0". How can I fix it and print exactly what is written on the file?

By the way, I know there are other forms to print a .txt exactly how it is made, I mean, I don't need 2D arrays to do this. However, I will use this program to read several matrixes and do some tests with them (also I want to print them as well), so I really need to store the data in a matrix of characters.


Solution

  • The problem is here.

       for (i = 0; ((i < N) && (temp = fgetc(arquivo)) != '\n') ; i++) {
            for (j = 0; j < N; j++) {
                A[i][j] = temp;
            }
        }
    

    The loop will exit once it sees a newline and start the while loop again.

    Instead you want to read N lines.

        for (i = 0; i < N; i++) {
            for(j = 0; (temp = fgetc(arquivo)) != '\n'; j++ ) {
                A[i][j] = temp;
            }
        }