除文本文件外,其他文件都可以看做是二进制文件,可以单独使用QFile读写二进制文件,但一般结合使用QFile和QDataStream读写二进制文件。
头文件部分主要代码
private:
QString m_filename;
template<class T> void writeByStream(T value);
template<class T> void readByStream(T &value);
cpp中主要实现代码
template <class T>
void MainWindow::writeByStream(T value)
{
QFile fileDevice(m_filename);
if(!fileDevice.open(QIODevice::WriteOnly))
return ;
QDataStream fileStream(&fileDevice);
fileStream.setVersion(QDataStream::Qt_6_8);
if(ui->radioBigEndian->isChecked())
{
fileStream.setByteOrder(QDataStream::BigEndian);
}
else {
fileStream.setByteOrder(QDataStream::LittleEndian);
}
if(ui->radiosinglePrecision->isChecked())
{
fileStream.setFloatingPointPrecision(QDataStream::SinglePrecision);
}
else
fileStream.setFloatingPointPrecision(QDataStream::DoublePrecision);
fileStream<<value;
fileDevice.close();
}
template <class T>
void MainWindow::readByStream(T &value)
{
if(!QFile::exists(m_filename))
return ;
QFile fileDevice(m_filename);
if(!fileDevice.open(QIODevice::ReadOnly))
return ;
QDataStream fileStream(&fileDevice);
fileStream.setVersion(QDataStream::Qt_6_8);
if(ui->radioBigEndian->isChecked())
{
fileStream.setByteOrder(QDataStream::BigEndian);
}
else {
fileStream.setByteOrder(QDataStream::LittleEndian);
}
if(ui->radiosinglePrecision->isChecked())
{
fileStream.setFloatingPointPrecision(QDataStream::SinglePrecision);
}
else
fileStream.setFloatingPointPrecision(QDataStream::DoublePrecision);
fileStream>>value;
fileDevice.close();
}
标签:fileDevice,qt,fileStream,读写,value,QDataStream,序列化,QFile,setFloatingPointPrecisio
From: https://blog.csdn.net/suntingsheng123/article/details/145214376