【问题标题】:C- reading string from binary file not workingC-从二进制文件中读取字符串不起作用
【发布时间】: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


【解决方案1】:

我没有尝试我的想法,但我认为您应该为名称字符串末尾的 \0 分配一个额外的字符。此外,您应该清除刚刚分配的字符串内存。 但我有点猜测。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2012-09-05
    • 2021-11-09
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多