I was trying to read a struct from a .text file and then save it in a new text file to see if it worked, but when it's getting saved the infamous error appears "run-time check failure #2 - stack around the variable 'pers' was corrupted". I don't know which size I should give to the struct persona pers in order for it to work. This is the .txt file:
Mirio Togata
18937332
15/7/1951
Shigaraki Tomura
17304739
24/11/1930
And this is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define LNOM 32
#define TAM 2 /*The size I established for the struct persona is 2 because there are 2 people*/
struct fecha { int d, m, a; };
struct persona
{
char nombre[LNOM];
int dni;
struct fecha nacim;
};
int readText(struct persona l[], int cant)
{
printf("Leyendo...\n");
char nom[LNOM];
FILE *pf = fopen("persona.txt", "r");
if (pf)
{
fgets(nom, LNOM, pf);
while (!feof(pf))
{
strcpy(l[cant].nombre, nom);
fscanf(pf, "%d", &l[cant].dni);
fgetc(pf);
fscanf(pf, "%d/%d/%d", &l[cant].nacim.d, &l[cant].nacim.m, &l[cant].nacim.a);
fgetc(pf);
cant++;
fgets(nom, LNOM, pf);
}
fclose(pf);
}
return cant;
}
void saveText(struct persona l[], int cant)
{
printf("Grabando...\n");
int i;
FILE *pf = fopen("personados.txt", "w");
if (pf)
{
for (i = 0; i < cant; i++)
{
fprintf(pf, "%s\n", l[i].nombre);
fprintf(pf, "%d\n", l[i].dni);
fprintf(pf, "%d/%d/%d\n", l[i].nacim.d, l[i].nacim.m, l[i].nacim.a);
}
fclose(pf);
}
}
int main(void)
{
int cant = 0;
struct persona pers[TAM];
cant = readText(&pers[TAM],cant);
saveText(&pers[TAM],cant);
return 0;
}
Thanks in advance.