Question

I'm trying to read some data from a binary file.

I have a struct set up that looks something like this:

struct track{
    unsigned long   ID;                             
    string      title;                      
};

And a file that stores values like

    [00000001][5468652054726163]
    [00000002][6F776C6F6F6B6174]

This is my terrible logic in somewhat pseudocode,

blocksize = 4;     // Read 4 bytes at a time

while(!endoffile){
    track[i].ID = (blocksize,pos)        // get 4 bytes starting at position
    track[i].title = blocksize*2,pos+4)  // get 8 bytes starting 4 after last position
    pos+12; i++;
}

I'm sorry, it's so bad. Like I said I'm new to C++. I know how to use fstream etc, it's just the logic of cycling through bytes in binary that throws me completely off.

Was it helpful?

Solution

You can do something like this:

#include <cstdint>
#include <fstream>
#include <string>

struct track { uint32_t id; char title[8]; };

std::ifstream infile("thefile.bin");

for (;;)
{
    track t;

    if (!infile.read(reinterpret_cast<char*>(&t.id), 4) ||
        !infile.read(t.title, 8)                        ||
        infile.gcount() != 8)
    {
        // error, die (or perhaps end of file)
    }

    // now you can use "t", e.g.:

    std::string title(t.title, 8);    // a sane string object
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top