1.写二进制文件
#include <QtCore/QCoreApplication> #include <QFile>
#include <QDataStream>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("file.dat");
if(!file.open(QIODevice::WriteOnly))
{
std::cerr<<qPrintable(file.errorString())<<std::endl;
return -1;
}
QDataStream stream(&file);
stream.setVersion(9);
QString id("ID:");
quint32 num(quint32(0x123456));
stream << id<< num;
file.close();
return a.exec();
}
2.类似读文件则是:
#include <QtCore/QCoreApplication> #include <QFile>
#include <QDataStream>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("file.dat");
if(!file.open(QIODevice::ReadOnly))
{
std::cerr<<qPrintable(file.errorString())<<std::endl;
return -1;
}
QDataStream stream(&file);
stream.setVersion(9);
QString id;
quint32 num;
stream >> id >> num;
std::cout<<id.toStdString()<<" "<<num<<std::endl;
file.close();
return a.exec();
}
感觉比较好的是直接可以读写字符串而不需要关心字符串长度 这个比较好
3.写文本文件
#include <QtCore/QCoreApplication> #include <QFile>
#include <QTextStream>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("output.txt");
if(!file.open(QIODevice::WriteOnly))
{
std::cerr<<qPrintable(file.errorString())<<std::endl;
return -1;
}
QTextStream stream(&file);
QString id("Eric Home.");
quint32 num(123456);
stream << id << num;
file.close();
return a.exec();
}
4.读文本文件
则可以通过设置编码方式 之后一次性读入或者以一个字符的模式读入