I recommend a process like that below.
Now, please note that you can re-work parsefile() for use only as a counter for first run--where no data is stored--just to first enquire how many values are to be captured in the file. Add a "which_pass" flag.
On the second pass, when data qty is known, allocate memory, and call parsefile() again.
Hope this is helpful.....
//---------------------------------------------------------------------
//
// get_field_offs()
//
// Find the offset of the desirred field in the buffer
//
//---------------------------------------------------------------------
int get_field_offs(char *s, int fld)
{
int i,len=strlen(s);
int tabs=0;
for(i=0; i< len; i++)
{
if(tabs>=fld) //stop if we hit required number of tabs
{
return i; //normal-usual exit
}
if(s[i]=='\t')
tabs++;
}
puts("ERR: get_field_offs()"); //user alert
return 0; //<<
//after all, zero (1st offset) is a valid value
}
//---------------------------------------------------------------------
//
// get_field()
//
// Function that returns a buffer having only the desired field.
// Strips leading spaces, tabs
//---------------------------------------------------------------------
char *get_field(char *s, int fld)
{
static char buff[100];
char *ps,*pd;
int done=0;
pd=buff;
ps=&s[get_field_offs(s, fld)];
while(*ps == ' ') //strip leading spaces, if exixst
ps++;
// Parse until 1st tab, etc
while(!done)
{
switch(*ps)
{
case '\0': //string terminator
case '\t': //tab
case '\r': //end of line character
case '\n': //end of line character
done=1;
break;
default:
*pd++=*ps++; // Collect normal chars, OK
break;
}
}
*pd=0; //Strip trailing junk
if(strlen(buff))
return buff;
return NULL;
}
//----------------------------------------------------------------------
//
// parsefile()
//
// Reads a file gathering data
//----------------------------------------------------------------------
void parsefile(FILE *fp)
{
char buff[300]; // make big enough to hold a line of data
int iii=0;
char *next_value=NULL;
double bigNumber;
long count=0;
memset(buff , '\0', sizeof(buff) );
fseek(fp, 0, SEEK_SET); //goto start of file
while(fgets(buff, sizeof(buff)-1, fp) != NULL)
{
for(iii=0; iii<1000; iii++) //note: '1000' is an arbitrary line length
{
next_value = get_field(buff, iii);
if(!next_value)
break; ///end of line -- no more data
bigNumber = atof( next_value );
count++;
///we've got the next number....do what you will with it--display, store...
printf("Next number is: %f\n", bigNumber);
}
}
printf("You'll need enough memory to hold %ld numbers.", count);
}