fread is reading too much
Everyone says that you can use fread to input a structure, right? For some reason this code doesn't work and I can't figure out what I'm doing wrong.
Code:
#include <stdio.h>
#include <string.h>
struct Data
{
char name[20];
int age;
};
int main()
{
FILE *IN;
struct Data *DATA = malloc(sizeof(struct Data));
memset (DATA->name, '\0', 80);
if ((IN = fopen("readFrom.txt", "r")) == NULL) {
puts("Input file could not be opened");
exit(0);
}
fread(DATA, sizeof(struct Data), 1, IN);
puts(DATA->name);
printf ("%d\n", DATA->age);
return 0;
}
When I run this it reads the whole name, the age, and a part of the name on the next line into just that one structure. I also figured that I needed to call free on DATA, but when I do I also get a debug error when I run the code. I've stepped through the code in my debugger and it looks like everything is being treated as a string and being placed in the 20 characters allocated for the array in the structure. Am I using fread wrong or is this all I can do?
Any help would be most appreciated