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

1) name is an uninitialized pointer. You have to allocate memory for it before it can be used as an input string (line 14). Just declare name as a character array instead of a pointer, such as char name[80]; line 11: There is no reason to make that variable a pointer since all you want is 10 floats. Just declare it as an array float array[10]; line 12: You can just delete this line if you make that variable an array of floats as above. In c++ programs you should use the new operator instead of malloc() or calloc().

1) name is an uninitialized pointer. You have to allocate memory for it before it can be used as an input string (line 14). Just declare name as a character array instead of a pointer, such as char name[80]; line 11: There is no reason to make that variable a pointer since all you want is 10 floats. Just declare it as an array float array[10]; line 12: You can just delete this line if you make that variable an array of floats as above. In c++ programs you should use the new operator instead of malloc() or calloc().

Thanks! This all worked great--such a simple solution. Just curious, what's the operator to use instead of malloc() or calloc()? I've just been programming for a few days and I've been teaching myself mostly from a mix of example c and c++ programs.

As Ancient Dragon has mentioned in his post, you should be using 'new' and 'delete' operators in C++.

malloc and free can be used in C.

Please click here for more information.

Okay, I see now. thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.