Datastream Qt to standard c++ code

1.6k views Asked by At

I created function Qt to read in a binary file, and it works.

[code]

    if (fileLoad.open(QIODevice::ReadOnly))
   {
   QDataStream in(&fileLoad);

   quint8 Variable_8bits;
   quint16 Variable_16bits;
   quint32 Variable_32bits;

   in >> Variable_16bits >> Variable_8bits >> Variable_32bits >> ZeroByte;

   qDebug() <<  Variable_16bits << Variable_8bits << Variable_32bits;

   //Works no extreme conversion necessary as i read input with "set size variables"
   // first 16bits, then 8bits, then 32bits
   // and store it correctly for display
   }
   fileLoad.close(); 
   }

So basically I could read in a binary file, using variables of different sizes to access the values in the file (Since I know the format of file structure)

My issue is that, now I need to create the same or similar functionality to a standard c++ function.

Is there a DataStream like Qt for C++ Or do I have to manually load file into buffer, then read in individual bytes, do bitwise manipulations to get the correct representation length, before i display the value or if there is a simpler method...

whats the way forward...

2

There are 2 answers

8
László Papp On

I would use std::ifstream for this simple use case presented as follows below.

However, note that the 8, 16, and 32 bit types were only added to the standard in C++11 and on.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{
    string line;
    ifstream myfile("example.txt", std::ios::binary);
    uint8_t Variable_8bits; // C++11 and on
    uint16_t Variable_16bits; // C++11 and on
    uint32_t Variable_32bits;  // C++11 and on
    if (myfile.is_open())
    {
        myfile.read(&Variable_16bits, 2);
        myfile.read(&Variable_8bits, 1);
        myfile.read(&Variable_32bits, 4)
        ...

        std::out << Variable_16bits << Variable_8bits << Variable_32bits;
        myfile.close();
    } else {
        cout << "Unable to open file"; 
    }

    return 0;
}
2
Marek R On

In standard C++ there is no function/class with functionality similar to QDataStream. Pleas note that QDataStream class provides support for multiple architectures, it take into account endians (by default assumes big endian), different standards of floating point values, it take control of sizes of build in types. (it also supports internalization and externalization of some Qt classes but this issue does not applies to standard C++)
In standard C++ all this platform diversity has to be handled manually (or by library).