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));
}
}
答案 0 :(得分:1)
只需使用结构来存储输入表和表格大小:
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);
}
答案 1 :(得分:0)
要做你想要的东西是非常昂贵的,因为你必须多次读完整个文件。相反,考虑制作动态的结构数组,当你用完房间时可以调整大小。
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),而不是struct data_t中的char **,你可以只使用所有mallocs和reallocs的struct输入*进行适当的更改结构的大小。
struct data_t当然只是您想要拥有的结构数组的标题,一个放置数组的位置,用于跟踪您拥有的结构数量,以及当前分配的空间大小。