c - 如何使用文件操作 malloc 结构数组来执行以下操作?

标签 c arrays file-io struct malloc

如何使用文件操作 malloc 结构体数组来执行以下操作? 该文件是.txt 文件中的输入如下:

10
22 3.3
33 4.4

我想从文件中读取第一行,然后我想分配一个输入结构数组等于要从文件中读入的行数。然后我想从文件中读入数据并读入结构数组 malloc。稍后我想将数组的大小存储到输入变量 size 中。返回一个数组。在此之后,我想创建另一个函数,以与输入文件相同的形式打印输入变量中的数据,并假设函数调用 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);

}

关于c - 如何使用文件操作 malloc 结构数组来执行以下操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482684/

相关文章:

C Array 存储错误问题

c - 读取字符串 C - Linux

arrays - 将一个数组选项取出一个周期

javascript - 获取 concat 以处理类似数组的对象

c - 随机数数组中的变量有问题

c - 在 C 中使用 fopen 进行迭代

java - 查找连续数量的 1

c++ - 从文本文件 C++ 加载结构 vector 的奇怪问题

.net - 使用 .NET 增强读取和解析文本文件的替代方案

更改文件描述符以将 STDOUT 通过管道传输到套接字?