I am trying to save a 2d array of characters to a file. My 2d array is a board where I can draw, resize, delete and add row/col.
I am facing a problem in saving it to a file.
First off, I don't know which of these two function is the faulty one. Is there a way to look up the .txt file that I'm trying saving it to and see if it worked?
Second, here are the two function, SAVE & LOAD to .txt file.
the name of the .txt file is passed on the parameter from the user. Please do ignore the "itreachedhere" print commands.
void save_board(char* textfile, board* theboard){
FILE* outfile = NULL;
int i,j;
outfile=fopen(textfile, "w");
if(outfile==NULL){
printf("Could not open file %s.\n", textfile);
}
printf("itreachedhere\n");
for(i=0;i<theboard->num_rows;i++){
for(j=0;j<theboard->num_cols;j++){
fprintf(outfile, " %c ", theboard->myboard[i][j]);
}
fprintf(outfile, "\n");
}
fclose(outfile);
}
void load_board(char* textfile, board* theboard){
FILE* infile = NULL;
int i, num_chars=0;
char current_char;
int lengths[10000];
int index=0;
int row=0;
infile=fopen(textfile, "r");
if(infile==NULL){
printf("Could not open file %s.\n", textfile);
// exit(1);
}
while(!feof(infile)){
current_char=fgetc(infile);
num_chars++;
//printf("%d ", num_chars);
if(current_char=='\n'){
// This array stores the length of characters of each line
lengths[index]=num_chars+1;
//update index
index++;
// Increment the number of row read so far
row++;
// Reset the number of characters for next iteration
num_chars=0;
}
}
//printf("%d",lengths[1]);
theboard->num_rows=row;
theboard->num_cols=lengths[0];
//recreate the board
createboard(theboard);
//now we need to copy the characters in infile to myboard
for(i=0;i<theboard->num_rows;i++){
fgets(theboard->myboard[i],(lengths[i]+1),infile);
//printf("%c", theboard->myboard[i][0]);
}
printf("itreachedhere\n");
printboard(theboard);
//printf("itreachedhere\n");
fclose(infile);
}
so, for example. If I have a board of size 4 x 5
3 * * * * *
2 * * * * *
1 * * * * *
0 * * * * *
0 1 2 3 4
I would then save it like so,
Enter your command: s e.txt
and load it like so,
Enter your command: l e.txt
then I would get something like this when I try to print out the board
3 � � � � � � � � � � � � � � � � �
2 � � � � � � � � � � � � � � � � �
1 � � � � � � � � � � � � � � � � �
0 � � � � � � � � � � � � � � � � �
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
there is nothing wrong with my printboard function. I think my fault is I don't know how to save the file correctly or retrieve the file correctly.
thanks for the comment. now i'm getting this
2 * * * *
1 * * * *
0 * * * *
0 1 2 3 4 5 6 7 8 9 10 11 12 13