0%

QT读取写入二进制文件

读写二进制文件

需要的头文件

1
2
3
4
5
#include <QMessageBox>
#include <QString>
#include <QPixmap>
#include <QFile>
#include <QDataStream>

写二进制文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool write_file(const QString &filename)
{
QFile file(filename);
if(!file.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this,tr("My App"),tr("Cannot write file %1:\n%2 .").arg(file.fileName()).arg(file.errorString()));
return false;
}

QDataStream out(&file);
out.setVersion(QDataStream::Qt_5_7);

out << qint32(0x1234abcd);

QApplication::setOverrideCursor(Qt::WaitCursor);

for (int i;i<100;i++)
out << quint16(i);

QApplication::setOverrideCursor(Qt::ArrowCursor);
return true;
}

读二进制文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
bool read_file(const QString &filename)
{
QFile file(filename);
if(!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(this,tr("My App"),tr("Cannot read file %1:\n%2.").arg(file.fileName()).arg(file.errorString()));
return false;
}

QDataStream in(&file);
in.setVersion(QDataStream::Qt_5_7);

//in << qint32(0x1234abcd);
qint32 magic;
in >> magic;

if (magic != 0x1234abcd)
{
QMessageBox::warning(this,tr("My App"),tr("This is not a correct file"));
return false;
}

QApplication::setOverrideCursor(Qt::WaitCursor);

quint16 temp;

while (!in.atEnd()) {
in >> temp;
ui->textEdit->setText(QString("%1").arg(temp));
}

QApplication::setOverrideCursor(Qt::ArrowCursor);
return true;
}
处无为之事,行不言之教;作而弗始,生而弗有,为而弗恃,功成不居!

欢迎关注我的其它发布渠道