How can I malloc an array of struct to do the following using file operation?
- by RHN
How can malloc an array of struct to do the following using file operation? the file is .txt input in the file is like:
10
22 3.3
33 4.4
I want to read the first line from the file and then I want to malloc an array of input structures equal to the number of lines to be read in from the file. Then I want to read in the data from the file and into the array of structures malloc. Later on I want to store the size of the array into the input variable size. return an array.After this I want to create another function that print out the data in the input variable in the same form like input file and suppose a function call clean_data will free the malloc memory at the end.
I have tried somthing like:
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));
}
}