1

I have a text file like this:

3 3 0

2 3 5

3 8 9

4 5 6

I want to put this numbers into a matrix. The first line are the numbers of rows and columns to make the malloc for the matrix. Then, the next lines are the numbers which are going to be on the matrix. And I have this code:

int mat[3][3];
int i, j;
FILE *fp;
char c;

if((fp = fopen("texto.txt", "r")) == NULL){
    printf("Error al abrir el archivo");
    return -1;
}

for(i=0;i<3;i++){
    for(j=0;j<3;j++){
        mat[i][j]=0;
    }
}

i = 0;
while (1)
{
    if (feof(fp))
        break;
    fscanf (fp, "%[^\n]%d %d %d", &mat[i][0], &mat[i][1], &mat[i][2]);
    i++;
}
fclose(fp);

for(i=0;i<3;i++){
    for(j=0;j<3;j++){
        printf("%d   ", mat[i][j]);
    }
    printf("\n");
}

(Sorry for the spanish lines)

I dont have the malloc written becouse i just want to see if I create the matrix correctly knowing that is a 3x3.

So the problem is that I dont know how to make the matrix from the second line of the text file, and dont use the first line.

Thanks!

1 Answers1

2

Read documentation of fscanf. Notice that spaces in the format control string may also skip newline characters, and that fscanf is returning the number of scanned items (which should matter to you). In some cases, you might be interested also by %n.

Be aware that your usage of fscanf is wrong (so is undefined behaviour) because %[^\n] expects an argument that you don't provide. With a good compiler like GCC, you should enable all warnings and debug info (e.g. compile with gcc -Wall -Wextra -g) and you'll get a warning.

If you want to skip the first line, start by reading every character (with fgetc) till you get EOF or '\n'. Or use fgets or getline(3) (on POSIX, like this) to read and ignore the first line.

If lines really matter, you could read every line (e.g. with fgets or getline(3)) and parse each line with e.g. sscanf or otherwise.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I know this is a wrong usage of fscanf, i was trying different options and i copy the last one, sorry. Ok, I will try it, thank u very much! – Mario Hernandez Jun 19 '17 at 11:16