I am trying to read a data file with this format:
2
2.0 5.8
4
-3.8 1.4 2.0 5.8
3
1.0 2.0 3.0
5
2.2 3.4 4.5 -1.0 2.0
The first number is the number elements and the numbers under are the elements. I would like to read the first number, then read that many elements into an array, and then go to the second set and read the first number, then that many elements after into an array, and so on and so on. I have started but I have gotten lost. Could someone please help me?
int main()
{
// Declare Variables
char temp[25];
int length;
// File Pointer
FILE *file;
// Open files and verify success
file = fopen("test.dat", "r");
if(file == NULL )
{
fprintf(stdout, "test.dat failed to open. exiting...\n");
exit(1);
while (!feof(file))
{
fgets(temp, 25, file); // Get length from file
length = atoi(temp); // convert string to integer
printf("Length is %d\n", length);
v_array(length, file);
}
fclose(file);
return 0;
}
// Function Definitions
float* v_array(int length, FILE *file)
{
int i;
char tmp;
float *array = NULL;
array = (float *) calloc(length, sizeof(float));
for(i = 0; i < length; i++)
{
fscanf(file, "%s", &tmp);
*array = atof(&tmp);
printf("v:%.2f\n", *array);
array++;
}
return array;
}