Tuesday, July 28, 2009

How to read (ASCII) data file in C

/*Function that reads the data file into an array and returns a pointer that points to this array of FP32*/

FP32* readData(const char *i_filename){

FILE *fp;
fp = fopen(i_filename, "r"); //open file , read only
INT32U numElements = 0;
FP32 value; //keep value at pointer position
FP32 *array=NULL; //set to NULL because of realloc
/* loop until all data keep into array */

while( (!feof(fp))){
fscanf(fp, "%f", &value);
array = (FP32 *) realloc (array,(numElements+1) * sizeof(FP32 *));
array[numElements++] = value;
}
/* shift array and add "size of array" to its first element
since there is no way to get size of an array from its FP32 pointer*/

INT32U i;
array = (FP32 *) realloc (array,(numElements+1) * sizeof(FP32 *));
for(i=numElements;i>0;i--){
array[i]=array[i-1];
}
array[0]=numElements;
/* close file */
fclose(fp);
return array;
}

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home