Qt: Write Struct to File

前端 未结 2 1602
面向向阳花
面向向阳花 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 <

    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<>pout;
            qDebug()<

    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.

提交回复
热议问题