I am trying to binary save strings from static character arrays and then print them. The point is that, in spite of the fact that I assign them the value in a static way (so when creating them, they should be created with the %code%
at the end, so I should not put it at hand). The biggest problem is that these arrays are part of a structure, so I have given a maximum value in the declaration of the same and then assign values. This structure seems to be saved correctly, but when reading the arrays, they do not print correctly. Here is the code:
The structure:
typedef struct
{
char P [250];
char R1 [250] ;
char R2 [250] ;
char R3[250] ;
} t_p_r;
The assignment of values to their arrays and the attempt to print them:
arrPreg =(t_p_r*)malloc(sizeof(t_p_r));
t_p_r preg;
strcpy(preg.P,"hola");
strcpy(preg.R1,"1");
strcpy(preg.R2, "2");
strcpy(preg.R3 ,"3");
arrPreg[0] = preg;
guardarPR(arrPreg,1);
pS = (t_p_r*)malloc(sizeof(t_p_r));
size = leerPR(pS);
for(int i=0; i<strlen(pS[0].P);i++)
{
printf("%c\n", pS[0].P[i] );
}
Methods for reading / writing:
void guardarPR(t_p_r P[], int numP)
{
FILE* fichero = fopen("PR.dat", "wb");
fputc(numP, fichero);
fwrite(&P, sizeof( t_p_r), numP, fichero);
fclose(fichero);
}
int leerPR(t_p_r* PL)
{
int numElem;
FILE* fichero = fopen("PR.dat", "rb");
numElem = fgetc(fichero);
PL= (t_p_r*) malloc((numElem) * sizeof(t_p_r));
fread(&PL, sizeof(t_p_r) , numElem, fichero);
fclose(fichero);
return numElem;
}
EDIT
Likewise, I have done another test, this time saving the structures individually. Although it gives a better result, it still does not work:
guardarSingular(preg);
t_p_r preg2;
leerSingular(&preg2);
printf(" %s\n", preg2.P);
printf(" %s\n", preg2.R1);
printf(" %s\n", preg2.R2);
printf(" %s\n", preg2.R3);
void guardarSingular(t_p_r PG)
{
FILE* fichero = fopen("PR.dat", "wb");
fputc(1, fichero);
fwrite(&PG, sizeof(t_p_r), 1, fichero);
fclose(fichero);
}
void leerSingular(t_p_r* PL)
{
FILE* fichero = fopen("PR.dat", "rb");
fread(PL, sizeof(t_p_r) , 1, fichero);
fclose(fichero);
}
Apparently, in view of the result, the structures seem to keep well, but at the time of reading and wanting to show them, they show strange characters different from those introduced at the beginning. How can I store this structure in a binary file in order to retrieve its strings as I saved them?