I have a binary file which contains records. The structure of the file is as such:
Structure (see below) Name String Address String
The structure in question:
typedef struct{
char * name;
char * address;
short addressLength, nameLength;
int phoneNumber;
}employeeRecord;
employeeRecord record;
I get the name as such:
char name[50];
printf("\nName:");
fgets(name,50,stdin);
record.nameLength = strlen(name)-1;
record.name = malloc(sizeof(char)*record.nameLength);
strcpy(record.name,name);
I write the structure, the the name, then the address (as mentioned above).
fwrite(&record.name,sizeof(char),record.nameLength,fp);
where fp is a file pointer.
Now i close the file. However, if i then want to read from the file to get this data back, I believe I need to read in the structure, read the nameLength variable, malloc enough memory for the name to sit in, then fread the name into the variable.
Like so:
char *nameString = malloc(sizeof(char)*record.nameLength);
fread(nameString,sizeof(char),record.nameLength,fp);
printf("\nName: %s",nameString);
However, when i attempt this, i do not get valid data. Example:
Input name is: Joseph (6 characters)
Output data:
Name length is 6 (correct),
Name is �A � (aka garbage)
So obviously im doing something wrong. Could someone give me some help?