I'm trying to write a very simple program to print out in the terminal the first 10 entries in a long binary file composed of floats. The idea is to make this work something like 'head' in the linux terminal (but for binary files). The problem I have is I get a 'segmentation fault.' As far as I can find, it's something related to closing the file. Here is my code:
#include <stdio.h>
#include <iostream>
using namespace std;
int main ()
{
int i;
char *name;
const char * fname;
float *array;
array = (float*)calloc(10,sizeof(float));
cout << "Enter a filename: ";
cin >> name;
fname = (const char*)name;
cout << "\n\n*******" << fname << "*******\n\n";
FILE * pFile;
pFile = fopen(fname,"rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);} // Exit with error message
fread(array,sizeof(float),10,pFile);
for (i=0;i<10;i++){
printf("%2i. % f\n",i+1,array[i]);
}
fclose(pFile);
return 0;
}
And here is what I get when I operate the program on the file 'adjusted_timeseries.bin':
Enter a filename: adjusted_timeseries.bin
*******adjusted_timeseries.bin*******
1. -1.470366
2. -1.398241
3. -1.612171
4. -2.791864
5. -0.540432
6. -0.798207
7. 1.061068
8. 0.320786
9. -0.771727
10. -1.118346
Segmentation fault