c - 从文件读取结构仅写入数组中的第一个结构

标签 c

我正在尝试将数据放入我的结构中,现在当我这样做时,只会将文件的第一行放入结构中。

我假设我不知道文件中有多少个名字。

int InputData(student ** p_array, FILE * fp) {
    student * arr;
    int i = 1;`

    if (!(arr = (student*)malloc(sizeof(student)))) {
        printf("no");
        _getch();
        exit(1);
    }
    while (fscanf(fp, "%s %d %d %d", arr[i - 1].name, &arr[i - 1].grades[0], &arr[i - 1].grades[1], &arr[i - 1].grades[2]) != EOF) {
        i++;
        if (!(arr = (student*)realloc(arr, i*sizeof(student))))
        {printf("no"); _getch(); exit(1); }
    }
    arr = (student*)realloc(arr, (i - 1) * sizeof(student));
    *p_array = arr;
    if (i = 1)
        return (i);       /*return the number of students*/
    else
        return (i - 1);
}

文件内容示例

 Moshe 100 80 90
 Dana 56 89 78
 Maya 88 87 91
 Adam 90 74 81

数组只获取这一行

 Moshe 100 80 90

请帮我修复代码。

最佳答案

如果稍微简化一下代码应该会更好:

int InputData(student **p_array, FILE *fp)
{
    student *arr;
    char buf[80];
    int i = 0;

    arr = (student *)malloc(sizeof(student));
    if (!arr) {
        printf("no");
        _getch();
        exit(1);
    }

    while (fscanf(fp, "%s %d %d %d", arr[i].name, &arr[i].grades[0], &arr[i].grades[1], &arr[i].grades[2]) != EOF) {
        i++;
        arr = (student *)realloc(arr, (i + 1) * sizeof(student));
        if (!arr)
            err(errno, "Failed realloc() array");
    }

    arr = (student *)realloc(arr, i * sizeof(student));
    *p_array = arr;

    return i;       /* return number of students */
}

关于c - 从文件读取结构仅写入数组中的第一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562033/

相关文章:

c - 我在数组中的指针无法按预期工作

c - ld 使我的所有函数都链接到头文件中的最后一个函数

c - 用 C 编写的服务器中最有效的文件登录是什么?

c - 为什么我不能在 C 中将 'char**' 转换为 'const char* const*'?

c - C中getopt的错误处理

c - 错误: Illegal Instruction. Mips交叉编译器

将char数组转换成类似于int argc和char** argv的结构

C 如何计算文本文件中唯一城市的数量

c - 什么是AST、CFG、CLANG,我们如何在deadcode去除算法中使用它们?

c - 使用 SQLite3 和 C 的段错误