1、缓冲区操作
- Qt 中缓冲区的概念
— 缓冲区的本质为一段连续的存储空间(字节数组代表连续存储空间)
— QBuffer 是 Qt 中缓冲区相关的类
— 在 Qt 中可以将缓冲区看做一种特殊的 IO 设备
— 文件流辅助类可以直接用于操作 缓冲区 - QBuffer 缓冲区的使用方式
- QBuffer 缓冲区的使用场合
1、在线程间进行不同类型的数据传递
2、缓存外部设备中的数据返回
3、数据读取速度小于数据写入速度
#include <QCoreApplication>
#include <QByteArray>
#include <QBuffer>
#include <QDataStream>
#include <QDebug>
void write_buf(int type, QBuffer& buf)
{
if(buf.open(QIODevice::WriteOnly))
{
QDataStream out(&buf);
out << type;
if(type == 0)
{
out << QString("D.T.Software");
out << QString("xiebs");
}
else if(type == 1)
{
out << 3;
out << 1415;
}
else if(type == 2)
{
out << 3.1415;
}
buf.close();
}
}
void read_buf(QBuffer& buf)
{
if(buf.open(QIODevice::ReadOnly))
{
QDataStream in(&buf);
int type = -1;
in >> type;
if(type == 0)
{
QString str1 = "";
QString str2 = "";
in >> str1;
in >> str2;
qDebug() << str1;
qDebug() << str2;
}
else if(type == 1)
{
int a = 0;
int b = 0;
in >> a;
in >> b;
qDebug() << a;
qDebug() << b;
}
else if(type == 2)
{
double value = 0;
in >> value;
qDebug() << value;
}
buf.close();
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray array;
QBuffer buf(&array);
write_buf(1, buf);
read_buf(buf);
return a.exec();