c - How to read a multi line using fscanf -
i want read data.txt file looks , store in array called buffer[i][j]
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
i writing code looks like
#include"stdio.h" #include"stdlib.h" int main() { file *fp1; int i,j; int buffer[4][4]={0}; fp1 = fopen("exact_enumerated_config_442_cub_mc","r"); for(i=0;i<4;i++) { for(j=0;j<4;j++) { fscanf(fp1,"%d", &buffer[i][j]); } // fscanf(fp1,"\n"); } fclose(fp1); for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("%d ",buffer[i][j]); } printf("\n"); } }
but output...
1 1 2 1
5 1 6 1
17 1 18 1
21 1 22 1
why????
- always check result of
fopen()
ensure file has been opened. - always check result of
fscanf()
ensure successful , prevent subsequent code processing variables may not have been assigned value (it returns number of assignments made). - add leading space character format specifier skip whitespace, including newline characters:
" %d"
.
the code treat single line sixteen int
s same 4 lines 4 int
s. if important format of file 4 int
s per line read single line using fgets()
, use sscanf()
extract int
s %n
format specifier ensure full buffer processed:
int ints[4][4] = { { 0 } }; char buffer[1024]; (int = 0; < 4 && fgets(buffer, 1024, fp); i++) { int pos; if (sscanf(buffer, "%d %d %d %d%n", &ints[i][0], &ints[i][1], &ints[i][2], &ints[i][3], &pos) != 4 || pos != strlen(buffer) - 1) { fprintf(stderr, "invalid format: <%s>\n", buffer); exit(1); } }