By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,171 Members | 1,037 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

Reading binary data from file

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Brad Marts" <ma***@phy.duke.edu> wrote...
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
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.