C语言 如何使用文件操作 malloc 结构数组以执行以下操作



如何使用文件操作来malloc 一个结构数组来执行以下操作?文件已.txt文件中的输入如下所示:

10
22 3.3
33 4.4
我想

从文件中读取第一行,然后我想对一个等于要从文件中读入的行数的输入结构数组进行 malloc。然后我想从文件和结构数组中读取数据 malloc。稍后我想将数组的大小存储到输入变量大小中。返回一个数组。在此之后,我想创建另一个函数,该函数以与输入文件相同的形式打印出输入变量中的数据,并假设函数调用clean_data将在最后释放malloc内存。

我尝试过类似的东西:

#include<stdio.h>
struct input
{
    int a;
    float b,c;
}
struct input* readData(char *filename,int *size);
int main()
{

return 0;
}
struct input* readData(char *filename,int *size)
{
    char filename[] = "input.txt";
    FILE *fp = fopen(filename, "r");
    int num;
    while(!feof(fp))
    {
        fscanf(fp,"%f", &num);
                struct input *arr = (struct input*)malloc(sizeof(struct input));
    }
}

只需使用结构来存储输入表和表大小:

typedef struct{
    int a, b;
    float c,d;
}Input;
typedef struct myInputs{
    uint size;
    Input* inputs;
}Input_table;

创建函数以写入或读取文件中的输入:

void addInput(Input_table* pTable, Input* pInput)
{
    pTable->inputs[pTable->size] = (Input*)malloc(sizeof(Input));
    memcpy((*pTable)->inputs[pTable->size], pInput); 
    pTable->size++;
}
Input* readInput(Input_table* pTable, uint index)
{
    if (pTable->size > index)
    {
        return pTable->inputs[index];
    }
    return NULL;
}

读取函数变为:

InputTable* readData(char *filename, int *size)
{
    Input_table myTable;
    FILE *fp = fopen(filename, "r");
    int num;
    while(!feof(fp))
    {
        Input newInput;
        fscanf( fp,"%d;%d;%f%f", &(newInput.a), &(newInput.b), &(newInput.c), &(newInput.d));
        addInput( &myTable, &newInput);
    }
}
// Here your table is filled in
printf("table size:%d", myTable.size);

}

做你正在寻找的事情是非常昂贵的,因为你必须多次通读整个文件。相反,请考虑创建一个动态结构数组,以便在空间不足时调整其大小。

    struct data_t {
            int nval;               /* current number of values in array */
            int max;                /* allocated number of vlaues */
            char **words;           /* the data array */
    };
    enum {INIT = 1, GROW = 2};
    ...
    while (fgets(buf, LEN, stdin)) {
            if (data->words == NULL)
                    data->words = malloc(sizeof(char *));
            else if (data->nval > data->max) {
                    data->words = realloc(data->words, GROW * data->max *sizeof(char *));
                    data->max = GROW * data->max;
            }
            z = strtok(buf, "n");
            *(data->words + i) = malloc(sizeof(char) * (strlen(z) + 1));
            strcpy(*(data->words + i), z);
            i++;
            data->nval++;           
    }
    data->nval--;

虽然这不是您需要的代码,但它非常接近,以至于根据您的问题进行调整应该很容易。代替 fgets(,,stdin),您将使用 fgets(,,fp),而不是在结构data_t中输入字符**,您只需放置一个结构输入*,所有 malloc 和 realloc 都会对结构的大小进行适当的更改。

当然,结构data_t只是您想要拥有的结构数组的标头,用于放置数组并跟踪您有多少以及当前分配了多少空间。