Reading binary files

I am trying to read a binary file and extract the data.
In the first part of the file there is an XML header with meta data. I haven't gotten to the part where I examine yet how to get past this and am working on the data itself for now.

I removed the header and am now left with the data itself and looking at it with a hex editor it appears to be 'long' followed by '0x00' then 'float'

I have tried various ways to read this in C++ and output the information but I just don't know what I am doing apparently.

This is my latest attempt. I was able to read it as character, but I don't know how to go beyond this.
So I'm looking for help, examples, places to go to read more about how to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
using namespace std;


int main () {
        ifstream file ("2009-02-09B.dat", ios::in|ios::binary);

        char ch;
        char level[4];
        char thetime[4];
        if(file.is_open())
        {
         while (!file.eof()) {
                file.get(level);
                file.get(ch);
                file.get(thetime);
                cout << (float) level << endl;
                cout << ch << endl;
                cout << (long) thetime << endl;
         }
          file.close();

        }
        else cout << "Unable to open file";
        return 0;
}



A little later::
After looking at this again, maybe I should be using a buffer with a pointer and to read 'float' at the reference. I think I'll give it a shot.

Last edited on
Copy and paste here some info of your text file if it's possible...
This is 10 lines of data.

 
C'$M^@E<80>]¾C&ýR^@E<82>@ßC&¼Û^@E<84>%^@C&{d^@E<86>^G¾C&¿[^@E<87>ëßC&<8f>á^@E<89>Í C&\è^@E<8b>±¾C&<8c>â^@E<8d><93> C&<88>â^@E<8f>x^@C&­Ý^@E<91>Y  
the binary mode read gives just raw files and there is no formatting of the characters. the way you are doing it, it wont give correct results. secondly you should know the boundries of the stream to read the binary file. lets take an example from your stream only:

C'$M^@E<80>]¾C&ýR^@E<82>@ßC


now lets say you are getting this and which is in this form:
bytes 0-3 data1(long)
bytes 4-7 data2(float)
bytes 8-15 data3(byte array or character array)

now how will you read it:
char buff[128];
long data1;
float data2;
char data3[16];

1
2
3
4
5
6
7
8
file.read(buff, 4); //this will read data1 in array, you need to make it to long
data1 = atol(buff);

file.read(buff, 4); //this will read data2
data2 = atof(buff); //convert to float

file.read(buff, 8);
strcpy(data3, buff); //created data3 


hope you are getting what i mean.. try on the same lines...
Topic archived. No new replies allowed.