Can someone tell me where I’m going wrong here? basically I’ve written some code that should take values from a file and then print the first value from the file as output along with the number of values in the file.
Although I get the correct number of values, my first value printed in the output isn’t the same as the first value in my file. here’s the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char Project_Data[] = "filedata.dat";
FILE *input = fopen(Project_Data, "r");
int t = 0;
int N = 0;
float *a;
a = (float*)malloc(N*sizeof(float));
if(input != (FILE*) NULL)
{
while(fscanf(input, "%e", &a[t]) == 1)
{
N++;
if(a[t] == EOF)
break;
}
printf("first value in file: %e\n",a[0]);
printf("number of values in file: %d\n", N);
}
else
printf("coudlnt read input file.\n");
return(0);
}
I feel it’s got something to do with how I’m using the malloc function. If so, how do I use it correctly? I want to read my values from the file into an array size N, but how can I do that if I don’t know the value of N beforehand?
EDIT:
Here’s some of the values from the file. The values are ordered one after the other with a single space between them. Because the number of values is quite large, they kind of form a several diagonals across the page (if you’ve it before).
9.0100000e+00 8.9663752e-01
9.0200000e+00 1.5041077e+00
9.0300000e+00 2.5992505e+00
9.0400000e+00 1.5242828e+00
9.0500000e+00 3.6815660e-01
9.0600000e+00 5.4889676e-01
9.0700000e+00 1.2371257e+00
9.0800000e+00 1.2163317e+00
9.0900000e+00 5.4318479e-01
9.1000000e+00 1.5906641e+00
9.1100000e+00 2.6775285e+00
9.1200000e+00 1.1608307e+00
9.1300000e+00 1.2084299e+00
9.1400000e+00 -7.8752191e-01
9.1500000e+00 6.4048690e-01
9.1600000e+00 2.2727416e-02
9.1700000e+00 1.0307653e+00
9.1800000e+00 1.9435864e+00
9.1900000e+00 2.9422693e+00
9.2000000e+00 3.2184945e+00
9.2100000e+00 1.3041157e+00
9.2200000e+00 1.1018038e+00
The values on the left aren’t orders; they are genuine values, it’s just the other data is meant to be the ‘noise’ in the data i think.
You can allocate an array with, say, 10 elements at first. While reading the file, remember to increase the index variable (t in your example). Should t become greater than your allocated size, use realloc to double the size of your array. This is how most dynamic vector implementations work as far as I know.
Something like this:
At this point
ashould contain your items andtthe number of items read.