I need to be able to read floats from a .DAT file. However, I do not want to assume that all of the lines will strictly be floats (comment lines, etc., are quite common in .DAT files that I use).
When I write the code to a file, the file contains the entire contents of my .DAT file correctly, but when I ask the program to display the contents of the array (buffer), it gives incorrect values. What am I doing wrong?
Here's the code:
Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]){
FILE* dataFile;
long file_size;
float* buffer;
size_t result;
int i;
dataFile = fopen (argv[1], "rb");
if (dataFile==NULL){
fputs ("File error", stderr);
exit (1);
}
// obtain file size:
fseek (dataFile, 0, SEEK_END);
file_size = ftell (dataFile);
rewind (dataFile);
// allocate memory to contain the whole file:
buffer = (float*) malloc (sizeof(float)*file_size);
if (buffer == NULL){
fputs ("Memory error", stderr);
exit (2);
}
// copy the file into the buffer:
result = fread (buffer, 1, file_size, dataFile);
if (result != file_size){
fputs ("Reading error", stderr);
exit (3);
}
/* the whole file is now loaded in the memory buffer. */
for (i=0; i<file_size; i++){
printf("%f\n", buffer[i]);
}
getch();
fclose (dataFile);
free (buffer);
return 0;
}