Reading binary data from file

B

Brad Marts

I have a file containing numbers stored in binary form and information in
ascii which tells me what kind of numbers they are (int, float, double,
etc.). I want to be able to read in the numbers and wind up with eg
vector<int> if the numbers are ints. It's not known until run-time what
the type of the numbers will be.

If I knew there would be 10 ints, I could write something like:

int numbers[10]
ifstream in("file.bin");
char line[256]

in.getline(line,255); // eg, the first line would contain "int\n"

in.read( (char *) &numbers, 10*sizeof(int));
in.close();

I could write a template function to do this, but I won't know until
run-time what the type will be. Do I have to use a switch to select which
function to use? Or is there a better way?

Brad
 
V

Victor Bazarov

Brad Marts said:
I have a file containing numbers stored in binary form and information in
ascii which tells me what kind of numbers they are (int, float, double,
etc.). I want to be able to read in the numbers and wind up with eg
vector<int> if the numbers are ints. It's not known until run-time what
the type of the numbers will be.

If I knew there would be 10 ints, I could write something like:

int numbers[10]
ifstream in("file.bin");
char line[256]

in.getline(line,255); // eg, the first line would contain "int\n"

in.read( (char *) &numbers, 10*sizeof(int));
in.close();

I could write a template function to do this, but I won't know until
run-time what the type will be. Do I have to use a switch to select which
function to use?

Pretty much.
Or is there a better way?

You could use an object of type std::map<string, myfunctionptr>,
which you should initialise with type identifiers and corresponding
function pointers, and then just call

mymap[line]( blah blah );

to read your array. Where are you going to store the array, anyway?
And how do you know which array to read? You will need to generalise
a bit more than just a function to call...

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top