I am trying to read integers from a txt file and store them in an 1D array.I have tried several ways but doesn't work correctly. My text file is below
1 2
2 1
3 2
2 1
1 2
2 1
3 2
2 1
1 2
2 1
3 2
2 1
Here is my code
#include <stdio.h>
#include <stdlib.h>
int main(void) // usually we write void when main doesn't take args
{
int i;
int j;
/*matrix*/
int *mat = malloc((12* 2* sizeof ( int))); // no casting!
FILE *file;
file=fopen("test.dat", "r"); // extension file doesn't matter
if(!file) {
printf("File not found! Exiting...\n");
return -1;
}
for(i = 0; i < 12; i++)
{
for(j = 0; j < 2; j++)
{
if (!fscanf(file, "%d", &mat[i*2 + j])){
printf("error!\n");
break;
}
//fscanf(file, "%d", &mat[i*2 + j]);
printf("ok!\n");
printf("%d \t",mat[i*2 + j]); // mat[i][j] is more clean
}
printf("\n");
}
free(mat);
fclose(file);
return 0;
}
Thank you for helping! ******UPDATE**** I figure out the first problem is that I couldn't read the file but then I found that I could only print one value which is 1 instead of 24 values there
./print_mat
ok!
1 error!
error!
error!
error!
error!
error!
error!
error!
error!
error!
error!
error!