Ok more code as asked.
int serialize_students(const Student *studArray, const int arrLength)
{
FILE *ptr_file;
int i=0;
ptr_file =fopen("output.txt", "w");
if (!ptr_file)
return -1;
for (i=0; i<arrLength; i++)
{
fprintf(ptr_file,"%d\n", studArray[i].id);
fprintf(ptr_file,"%s\n", studArray[i].name);
fprintf(ptr_file,"%d\n", studArray[i].gender);
}
fclose(ptr_file);
return 0;
}
int deserialize_students(Student *dest, const int destCapacityMax)
{
FILE *ptr_file;
int i=0;
ptr_file =fopen("output.txt","r");
if (!ptr_file)
return -1;
if(destCapacityMax==0)
return -2;
while (!feof (ptr_file))
{
fscanf (ptr_file, "%d", &dest[i].id);
fscanf (ptr_file, "%s", dest[i].name);
fscanf (ptr_file, "%d", &dest[i].gender);
i++;
if(i==destCapacityMax)
return 0;
}
fclose(ptr_file);
return 0;
}
void print_student(Student student)
{
printf("id: %d\n", student.id);
printf("name: %s\n", student.name);
printf("gender: %d\n", student.gender);
}
void print_students(const Student *studArray, const int arrLength)
{
int i = 0;
for(i =0; i<5;i++)
{
print_student(studArray[i]);
}
}
main
typedef struct student
{
int id;
char name[100];
int gender;
}Student;
int main()
{
int i = 0;
Student dest[5];
Student students[5];
memset(dest,0,sizeof(dest));
memset(students,0,sizeof(students));
/* Initialize students */
/*for(i = 0; i<5; i++)
{
students[i].id = i;
strcpy(students[i].name,arr[i]);
students[i].gender = MALE;
}*/
/*Serialize*/
serialize_students(students,5);
/* Reconstruct student array from file */
deserialize_students(dest, 5);
/* Print reconstructed array of students */
print_students(dest,5);
return 0;
}
My question is: see how the data is written in file, and see how it is printed on console? Why they differ? Why only first three values of name show 0? but other two empty?
This is how file looked like
This is console output: