Another beginner problem I'm afraid. the intention is to create a 3D array of strings, fill each string with an initial value that identifies it, (to aid with later manual filling of array elements) and save it to a file. Then to recover an individual element, pre-filled with its initial value for editing.
the problem is the program is returning nonsense when I when I try to extract an individual string from the array.
I dont know if the problem is with the storing or extracting the array or both.
The code snippet below seems long, but I have needed to include both the read and write sections.
#include <stdio.h>
#include <string.h>
#define ELEMENT_SIZE 16
struct data_cell
{
char my_data[2][2][2][ELEMENT_SIZE];
int element_num[3];
};
void main()
{
/** for writing**/
struct data_cell save;
int x , y , z;
char d[] = {'0'};
/** for reading **/
struct data_cell from_file;
int dimensions[2];
int a,b,c ;
char path[] = "C:\\Users\\dave\\Documents\\data.txt";
FILE *fp ;
if ((fp = fopen(path,"w")) == NULL)
{
printf("cannot open file");
exit(1);
}
for(x=0 ; x< 2 ; x++)
for(y =0 ; y < 2 ; y++)
for(z =0 ; z < 2 ; z++)
{
strcpy(save.my_data[x][y][z],"element is at ");
save.my_data[x][y][z][8] = d[0];
d[0]+=1;
save.element_num[0] = x;
save.element_num[1] = y;
save.element_num[2] = z;
//fprintf(fp,"%s[%d][%d][%d] " ,save.my_data[x][y][z] , save.element_num[0] , save.element_num[1] ,save.element_num[2] );
printf("data_cell %s[%d][%d][%d]\n" ,save.my_data[x][y][z] ,save.element_num[0] ,save.element_num[1] ,save.element_num[2] );
}
fwrite(&save, sizeof(save), 1 , fp);
fclose(fp);
/** reading **/
if ((fp = fopen(path,"r")) == NULL)
{
printf("cannot open file");
exit(1);
}
printf("enter array element to be read eg 1 2 1"); /** Range 0-2, press return between each**/
scanf("%d %d %d" , &dimensions[0] , &dimensions[1] , &dimensions[2] );
a = dimensions[0];
b = dimensions[1];
c = dimensions[2];
fread(&from_file , sizeof(from_file) ,1 ,fp );
printf("data_cell.my_data[%d][%d][%d] contains %s", a ,b ,c, from_file.my_data[a][b][c]);
fclose(fp);
}
int dimensions[2];have onlydimensions[0]anddimensions[1].dimensions[2]is out-of-range."element is at "because there are no room for terminating null-character.snprintfand make sure you have enough space in the buffer.