Qt读写二进制文件

DataStream.h
#ifndef DATASTREAM_H
#define DATASTREAM_H
#include <QDataStream>
#include <QString>

class A{
private:
    int a1;
    QString a2;
public:
    A(){
        a1 = 0;
        a2 = QString();
    }

    A(int v1,QString v2){
        a1 = v1;
        a2 = v2;
    }
    int getA1()const{
        return a1;
    }
    QString getA2()const{
        return a2;
    }
};

QDataStream& operator<<(QDataStream& out,const A& a);
QDataStream& operator>>(QDataStream& in,A& a);

#endif // DATASTREAM_H



DataStream.cpp
#include "DataStream.h"
#include <QFile>
#include <iostream>
using namespace std;

QDataStream& operator<<(QDataStream& out,const A& a){
    int a1 = a.getA1();
    QString a2 = a.getA2();
    out << a1;
    out << a2;
    return out;
}

QDataStream& operator>>(QDataStream& in,A& a){
    int a1;
    QString a2;
    in >> a1;
    in >> a2;
    a = A(a1,a2);
    return in;
}

int main(){
    A a(10,"abc");
    QString fileName = "test.dat";
    QFile writeFile(fileName);
    writeFile.open(QIODevice::WriteOnly);
    QDataStream out(&writeFile);
    out << a;
    writeFile.close();

    QFile readFile(fileName);
    readFile.open(QIODevice::ReadOnly);
    QDataStream in(&readFile);
    A a2;
    in >> a2;
    readFile.close();
    cout << "a1:" << a2.getA1() << ",a2:" << a2.getA2().toStdString() << endl;
}

a1:10,a2:abc

你可能感兴趣的:(二进制)