Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QDataStream read from a specific sequence



  • Hi,
    i save some informations as binary data into a file. I serialize the data with the QDataStream class.

    QFile file("export.dat");
    file.open();
    
    QDataStream stream(&file);
    stream << QString("Header1");
    stream << m_value1 << m_value2;
    
    stream << QString("Header2");
    stream << m_value3 << m_value4;
    
    file.close();
    

    And read it with:

    QFile file("export.dat");
    file.open();
    
    QDataStream stream(&file);
    QString header1;
    stream >> header1;
    
    double m_value1, m_value2;
    stream >> m_value1 >> m_value2;
    
    QString header2;
    stream >> header2;
    
    double m_value3, m_value4;
    stream >> m_value3 >>m_value4;
    
    file.close();
    

    I search a way just to read the values after Header2. Is there a way like

    QFile file("export.dat");
    file.open();
    
    QDataStream stream(&file);
    
    bool ok = stream.readFrom(QString("Header2"));
    double m_value3, m_value4;
    stream >> m_value3 >>m_value4;
    

    Or do just need to read the file as byte array and search for the Header2 sequence?

    Thanks for any advice.

    Edit:

    My solution:

    QFile file("export.dat");
    file.open();
    
    QByteArray bytes = file.readAll();
    
    QByteArray headerAsBytes;
    QDataStream headerStream(&headerAsBytes, QIODevice::WriteOnly);
    headerStream << QString("Header2");
    int startIndex = bytes.indexOf(headerAsBytes);
    
    QDataStream stream(&bytes, QIODevice::ReadOnly);
    stream.skipRawData(startIndex);
    
    QString header2;
    stream >> header2;
    
    double m_value3, m_value4;
    stream >> m_value3 >>m_value4;
    

    The section where the header2 - QString is converted as QByteArray is really ugly, but it works for me.


Log in to reply