maybe this is a very easy question but I'm confused
If my code is named example.c and takes as an input a txt file, lets say txt.txt
. I run the command ./example txt.txt
in a terminal (linux).
According to what the user gives me through the file, I create a 2D array.
If the context of the fie is:
+X..XX....-
.X..X..X-..
.X.........
...XX......
XXX.+X.....
..X.....XXX
...XXX..X-.
.-.....X...
I count the lines (in this example 1) and the elements before the new line, to find the rows of my array.
Can you please tell me what I do wrong in the printing of the file into a 2d array?
I can't print the array properly.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
int lines=0, rows=0, j, k;
char ch, array[1000][1000];
FILE *fin;
if(argc!=2){
exit(2);
}
fin=fopen(argv[1],"r");
if(fin==NULL) {
exit(2);
}
while(!feof(fin)){
ch=fgetc(fin);
if(ch=='\n') lines++;
}
fclose(fin);
fin=fopen(argv[1],"r");
while(!feof(fin)){
ch=fgetc(fin);
if(ch=='+' ||ch=='-'|| ch=='.'||ch=='X') rows++;
if(ch=='\n') break;
}
printf("%d %d\n", lines, rows);
fclose(fin);
fin=fopen(argv[1],"r");
while(!feof(fin)) {
for(j=0; j<lines; j++){
for(k=0; k<rows; k++){
scanf(fin, "%c", &array[j][k]);
}
}
//printf("%d %d", lines, rows);
int i;
for(i=0; i<lines; i++){
for(j=0; j<rows; j++){
printf("%c", array[i][j]);
//printf("%d %d\n", i, j);
}
}
fclose(fin);
return 0;
}
}