I have a struct employee
:
typedef struct employee
{
int name_length;
char* name;
float salary;
} Employee;
Now I want to make an array of employees, and get it from a binary file for each employee the name, and salary. (binary file scheme is built like: 6michel7544.564
(length of name, name itself, salary) and so on with unknown number of employees).
I built this function to build the array:
Employee** makeEmpArray(char* fname1, int* size)
{
FILE* empFile;
int k = 0;
Employee** arr; //array of employees
arr = (Employee**)malloc(sizeof(Employee*));
assert(arr != NULL);
empFile = fopen(fname1, "rb");
if (ferror(empFile))
{
printf("Error, cant open file");
exit(2);
}
while (!feof(empFile))
{
arr[k] = (Employee*)malloc(sizeof(Employee));
assert(arr[k]);
fread(&(arr[k]->name_length), sizeof(int), 1, empFile); // get length of name
arr[k]->name = (char*)malloc(arr[k]->name_length * sizeof(char)); //allocate memory for name in namelength size
assert(arr[k]->name!=NULL);
fread(arr[k]->name, sizeof(char), arr[k]->name_length, empFile); //read letter letter (namelen times)
fread(&arr[k]->salary, sizeof(float), 1, empFile); //reads floeat salary
k++;
arr = realloc(arr, (k + 1) * sizeof(Employee*)); //realloc for next employee
assert(arr != NULL);
}
fclose(empFile);
*size = k;
return arr;
}
and every thing is going well except the string of the name!
I get the name_length
perfectly, I get the salary perfectly, and for some reason this line is the problematic:
fread(arr[k]->name, sizeof(char), arr[k]->name_length, empFile);
The name does not read from the file. No error is prompt, and when I watch arr[k]->name
when debugging I see <invalid characters in string.>
Hope you could help me identify the problem!