I am trying to read a data file with this format:

2.0 5.8

-3.8 1.4 2.0 5.8

1.0 2.0 3.0

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");

	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);

	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);

	return array;
Votes + Comments
Thanks for using code tags correctly on the first attempt :)
7 Years
Discussion Span
Last Post by Ancient Dragon

line 19: missing closing } character to close out that if statement

line 49: incrementing that pointer just destroyed the memory that was allocated on line 42. You must never change an allocated pointer. If you want to use pointer arithmetic (increment and decrement) then use a different pointer. I would suggest you don't use a pointer at all, but use the loop i counter to index into the array.

line 46 and 47 can be combined: fscanf( file, "%f", &array[i] ); The next problem is what are you doing to do that that array after reading the data? You have to save it somewhere so that it can be used again later in the program.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.