【发布时间】:2020-05-23 18:27:41
【问题描述】:
我有一个struct employee:
typedef struct employee
{
int name_length;
char* name;
float salary;
} Employee;
现在我想创建一个员工数组,并从二进制文件中获取每个员工的姓名和薪水。 (二进制文件方案的构建类似于:6michel7544.564(姓名长度、姓名本身、工资)等等,员工人数未知。
我构建了这个函数来构建数组:
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;
}
除了名字的字符串之外,一切都很顺利!
我完美地得到了name_length,我完美地得到了薪水,但由于某种原因,这条线是有问题的:
fread(arr[k]->name, sizeof(char), arr[k]->name_length, empFile);
名称不会从文件中读取。没有错误提示,调试的时候看arr[k]->name看到<invalid characters in string.>
希望您能帮我找出问题所在!
【问题讨论】:
-
无效字符出现在哪里?在正确的名称之后,例如“michel%$!”?您的
name不是以空值结尾的。再分配一个字符,然后将实际名称后面的字符设置为'\0'。 (我怀疑你读名字失败的时候能不能正确读工资。) -
@KamilCuk 那你怎么解释这个
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? -
迈克尔,你能用@KamilCuk修复再试一次吗?
-
@MacOS 好吗?
fread不读取以 10 为基数的数字表示,它读取任何字节。 OP 应该将表示数字的 ASCII 字符转换为本机机器表示。通常使用scanf完成。生成的arr[k]->name不是以零结尾的,name_length不等于6但等于 ASCII 字符'6'和arr[k]->salary很可能不包含float的有效表示。
标签: c struct binaryfiles