Qt: Write Struct to File

前端 未结 2 1515
面向向阳花
面向向阳花 2021-01-27 11:09

I\'m struggling with writing a struct to a file via QFile in Qt.

typedef struct {
    uint32_t timestamp;
    uint32_t recordType;
             


        
相关标签:
2条回答
  • 2021-01-27 11:33

    Another thing is that to keep Qt compatibility rename some native types, so I recommend using equivalent types, in addition to using QString directly instead of char * payload and payloadLength as shown below:

    struct DataPacket{
        quint32 timestamp;
        quint32 recordType;
        QString payload;
    };
    

    Also when writing it is better to use QDataStream as shown below:

    QDataStream &operator>>(QDataStream &in, DataPacket &p){
        in >> p.timestamp >> p.recordType >>p.payload;
        return in;
    }
    
    QDataStream &operator<<(QDataStream &out, const DataPacket &p){
        out << p.timestamp << p.recordType <<p.payload;
        return out;
    }
    

    The following example shows its use:

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        const QString fileName = "file.log";
    
        QString dataString = "$GPGSA,M,3,03,23,22,19,17,01,09,31,12,,,,1.9,0.9,1.6*3D";
    
        DataPacket pin{1000, 123, dataString};
    
        QFile fout(fileName);
        if(fout.open(QIODevice::WriteOnly)){
            QDataStream out(&fout);
            out<<pin;
        }
        fout.flush(); // or fout.close();
    
        DataPacket pout;
        QFile fin(fileName);
        if (fin.open(QIODevice::ReadOnly)) {
            QDataStream in(&fin);
            in>>pout;
            qDebug()<<pout.timestamp<<pout.recordType<<pout.payload;
        }
        return 0;
    }
    

    Output:

    1000 123 "$GPGSA,M,3,03,23,22,19,17,01,09,31,12,,,,1.9,0.9,1.6*3D"
    

    Note: QDataStream sets payloadLength indirectly because it knows the size of QString.

    0 讨论(0)
  • 2021-01-27 11:55

    Much simpler:

    assuming your structure 'DataPacket'

    void MyClass::write()
    {
    QFile out(FILE_PATH_NAME);
    out.open(QIODevice::WriteOnly);
    out.write((const char *)DataPacket,sizeof(DataPacket));
    out.close();
    }
    
    void MyClass::read()
    {
    QFile in(FILE_PATH_NAME);
    in.open(QIODevice::ReadOnly);
    in.read((const char *)DataPacket,sizeof(DataPacket));
    in.close();
    }
    
    0 讨论(0)
提交回复
热议问题