x.h
QFile file("D:/testimage/text.dat");
if (!file.open(QIODevice::WriteOnly)){
std::cerr <<"cannot open file for writing:"
<<qPrintable(file.errorString())<<std::endl;
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_5_12);
in>>n>>image>>map;
qDebug()<<"ok";
x.cpp
#include "widget.h"
#include <QtWidgets>
#include<iostream>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
//读取二进制文件
QImage image("D:/testimage/mouse.jpg");
QMap<QString , QColor> map;
map.insert("red",Qt::red);
map.insert("green",Qt::green);
map.insert("blue",Qt::blue);
QFile file("D:/testimage/text.dat");
if (!file.open(QIODevice::WriteOnly)){
std::cerr <<"cannot open file for writing:"
<<qPrintable(file.errorString())<<std::endl;
return;
}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_5_12);
out<<quint32(0x12345678)<<image<<map;
qDebug()<<"ok";
}
void Widget::test()
{
quint32 n;
QImage image;
QMap<QString , QColor> map;
QFile file("D:/testimage/text.dat");
if (!file.open(QIODevice::WriteOnly)){
std::cerr <<"cannot open file for writing:"
<<qPrintable(file.errorString())<<std::endl;
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_5_12);
in>>n>>image>>map;
qDebug()<<"ok";
}
//读取普通文本文件
void Widget::NewText()
{
QFile file("D:/testimage/text.txt");
if (!file.open(QIODevice::WriteOnly)){
std::cerr <<"cannot open file for writing:"
<<qPrintable(file.errorString())<<std::endl;
return;
}
QTextStream out(&file);
out<<"Hello "<<"Qt!"<<endl;
}
Widget::~Widget()
{
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
//w.test();
w.NewText();
w.show();
return a.exec();
}