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

QFile - read bytes, x at a time, x +offset?



  • Hey

    I'm trying to read part of the file to decide if I wish to read all of the file... can any1 help me out fill in the blank?

        QByteArray someData;
        QByteArray da;
        QDataStream s(&da, QIODevice::WriteOnly);
        s << (int) 1412 << (quint16) 123143 << (bool) true << (int) someData.size() << someData;
        QFile f(path);
        if (f.open(QIODevice::ReadOnly)) {
            int initial = 0;
            quint16 qinitial = 0;
            bool good = false;
            int dataSize = 0;
            QByteArray inData = f.read(sizeof(int) + sizeof(quint16) + sizeof(bool) + sizeof(int));/// Is this correct?
    
            QDataStream in(&inData,QIODevice::ReadOnly);
            in>>initial>>qinitial>>good>>dataSize;
            if(good){
                /// Read f.read(dataSize) ??? How to read rest?
            }
        }
    

    TIA



  • @Dariusz Why you not simply use a QDataStream from file?

        QByteArray someData;
        QByteArray da;
        QDataStream s(&da, QIODevice::WriteOnly);
        s << (int) 1412 << (quint16) 123143 << (bool) true << (int) someData.size() << someData;
        QFile f(path);
        if (f.open(QIODevice::ReadOnly)) {
            QDataStream inData(&f);
            int initial;
            quint16 qinitial;
            bool good;
            int dataSize;
    
            inData>>initial>>qinitial>>good>>dataSize;
            if(good){
                QByteArray buffer;
                buffer.resize(dataSize);
                inData.readRawData(buffer.data(), dataSize);
            }
        }
    


  • @KroMignon looks interesting, but I want to read from xx byte to xx byte. Not all of it.

    Also ohh hmmmm that looks interesting, did not know I can do it. So if I do dataStream, hell only read specific bytes automaticly? Damn thats neat o.o / still what about reading just xx to xx ?

    Hmm I suppose I could just use skiPrawData(int) < I guess its skipRawData(sizeof(int)) or just the size I stored early.


  • Qt Champions 2019

    @Dariusz Simply seek to the position where you want to read and then read the amount of bytes you need.
    https://doc.qt.io/qt-5/qfiledevice.html#seek
    https://doc.qt.io/qt-5/qiodevice.html#read-1

    You can seek to the beginning of the file if you decide to read whole file.