Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Binary Files into an array of ints c++

I have a method which writes a binary file from an int array. (it could be wrong too)

void bcdEncoder::writeBinaryFile(unsigned int packedBcdArray[], int size)
{
    fstream binaryIo;
    binaryIo.open("PridePrejudice.bin", ios::out| ios::binary | ios::trunc);
    binaryIo.seekp(0);
    binaryIo.write((char*)packedBcdArray, size * sizeof(packedBcdArray[0]));
    binaryIo.seekp(0);

    binaryIo.close();
}

I need to now read that binary file back. And preferably have it read it back into another array of unsigned ints without any information loss.

I have something like the following code, but I have no idea on how reading binary files really works, and no idea how to read it into an array of ints.

void bcdEncoder::readBinaryFile(string fileName)
{
    // myArray = my dnynamic int array

    fstream binaryIo;
    binaryIo.open(fileName, ios::in | ios::binary | ios::trunc);

    binaryIo.seekp(0);

    binaryIo.seekg(0);
    binaryIo.read((int*)myArray, size * sizeof(myFile));

    binaryIo.close();
}

Question:

How to complete the implementation of the function that reads binary files?

like image 874
Justin Tennant Avatar asked Oct 27 '25 23:10

Justin Tennant


1 Answers

If you're using C++, use the nice std library.

vector<unsigned int> bcdEncoder::readBinaryFile(string fileName)
{
    vector<unsigned int> ret; //std::list may be preferable for large files
    ifstream in{ fileName };
    unsigned int current;
    while (in.good()) {
        in >> current;
        ret.emplace_back(current);
    }
    return ret;
 }

Writing is just as simple (for this we'll accept an int[] but an std library would be preferable):

void bcdEncoder::writeBinaryFile(string fileName, unsigned int arr[], size_t len)
{
    ofstream f { fileName };
    for (size_t i = 0; i < len; i++)
        f << arr[i];
}

Here's the same thing but with an std::vector

void bcdEncoder::writeBinaryFile(string fileName, vector<unsigned int> arr)
{
    ofstream f { fileName };
    for (auto&& i : arr)
        f << i;
}
like image 127
Olipro Avatar answered Oct 29 '25 15:10

Olipro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!