Hi All.. i am reading a file Containg integers and i want to store in 2D array. here is my code,but when i Execute my code i get all of my 2D array fill with Zero. Could you Help me in finding My Error. thanks. Code: #include<stdio.h> #define MAX_COL 10 #define MAX_ROW 16 int Board[MAX_ROW][MAX_COL]; void print_Board() { int Col,Row; for (Row=0; Row<MAX_ROW; Row++) { for (Col=0; Col<MAX_COL; Col++) { printf("%d",Board[Row][Col]); } printf("\n"); } } int Read_File() { char c; int Col=0; int Row=0; FILE *fp; fp=fopen("game.txt","r"); if(fp==NULL) return -1; while( !feof(fp) ) { c=fgetc(fp); if(c>='0' && c<='9') { Board[Row][Col]=c - '0'; Col++; if(Col>=MAX_COL) { Row++; Col=0; } if(Row>=MAX_ROW) return 1; } } fclose(fp); return 1; } int main() { int chk; chk=Read_File(); print_Board(); getch(); return 0; } My text file is... 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790 1234563790
The program works fine for me. Are you sure that you are really opening the file? You test to see if the file opens and if not return -1 to the calling function but you never use that -1 in the calling function to inform the user that the input file could not be opened. Jim
Code: int main() { int chk; chk=Read_File(); if(chk<0) printf("file not opened\n"); print_Board(); getch(); return 0; } thanks jim,but i find all zeros in ma 2D array. i m just reading a file
when you see zeroes it means that either your file is full of then or the file doesn't exist. in your code you tried to fix it but you didn't. Code: if(chk<0) printf("file not opened\n"); [COLOR=Red]else[/COLOR] print_Board(); no if the file isn't there you see nothing
You could file the array with another number before reading the file Code: void fill_Board() { int Col,Row; for (Row = 0; Row < MAX_ROW; Row++) { for (Col = 0; Col < MAX_COL;Col++) { Board[Row][Col] = 1; } } } and then add Code: fill_Board(); just before Code: chk=Read_File(); and if it's full of 1 then it can not be reading/opening the file