1. 程式人生 > >qt中普通二進位制檔案的讀寫

qt中普通二進位制檔案的讀寫

1、檔案的開啟

QString filePath = getPath();
	QString fileName = QString("%1/%2_%3.air").arg(filePath).arg(uasName).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss"));
	this->m_file = new QFile(fileName);
	m_file->open(QIODevice::WriteOnly);

利用檔案的路徑+名字開啟一個新檔案,同名檔案存在時開啟,不存在時新建。 然後需要選擇開啟的方式(檔案的讀寫都需要開啟檔案)

2、檔案的寫入

QByteArray arr;
		{
			quint8 array[8] = { 0,0,0,0,0,0,0,0 };
			qToLittleEndian<double>(info.getValuelat(), array);
			for (int i = 0; i < 8;i++)
			{
				arr.append(array[i]);
			}
		}
		{
			quint8 array[8] = { 0,0,0,0,0,0,0,0 };
			qToLittleEndian<double>(info.getValuelng(), array);
			for (int i = 0; i < 8; i++)
			{
				arr.append(array[i]);
			}
		}
				this->m_file->write(arr);
		this->m_file->flush();

把要寫入的資料根據不同型別分別加入到array中,再將array寫入檔案。 flush()函式是使檔案即時寫入。 如果在開啟檔案的時候將寫入了檔案的頭,在寫內容時,要跳過頭部長度:

if(this->m_file->open(QIODevice::WriteOnly))
    {
        this->m_file->write(ROFLYING_SPRAY_HISTORY_SIGNAL);

		QByteArray buff;
		{
			quint8 array[8] = { 0,0,0,0,0,0,0,0 };
			qToLittleEndian<double>(sprayWide, array);
			buff.append(array[0]);
			buff.append(array[1]);
			buff.append(array[2]);
			buff.append(array[3]);
			buff.append(array[4]);
			buff.append(array[5]);
			buff.append(array[6]);
			buff.append(array[7]);
		}

		{
			double sprayArea = 0.0f;
			quint8 array[8] = { 0,0,0,0,0,0,0,0 };
			qToLittleEndian<double>(sprayArea, array);
			buff.append(array[0]);
			buff.append(array[1]);
			buff.append(array[2]);
			buff.append(array[3]);
			buff.append(array[4]);
			buff.append(array[5]);
			buff.append(array[6]);
			buff.append(array[7]);
		}

		quint8 uasSize1 = uasName.toLocal8Bit().size();
		{
			quint8 array[1] = {0};
			qToLittleEndian<quint8>( uasSize1, array);
			buff.append(array[0]);
		}

		buff.append(uasName.toLocal8Bit());


		this->m_file->write(buff);
		this->m_file->flush();
    }
    else
    {
        this->close();
    }
if (this->isOpen())
	{
		this->m_file->seek(16);

		QByteArray buff;
		quint8 array[8] = { 0,0,0,0,0,0,0,0 };
		qToLittleEndian<double>(area, array);
		buff.append(array[0]);
		buff.append(array[1]);
		buff.append(array[2]);
		buff.append(array[3]);
		buff.append(array[4]);
		buff.append(array[5]);
		buff.append(array[6]);
		buff.append(array[7]);

		this->m_file->write(buff);
		this->m_file->flush();
		this->m_file->seek(this->m_file->size());
	}

3、檔案的讀取

if (file.open(QIODevice::ReadOnly))
	{
		QByteArray data;
		data = file.read(ROFLYING_AIR_HISTORY_INFO_LENGTH);
		while (data.length() == ROFLYING_AIR_HISTORY_INFO_LENGTH)
		{
			quint8 *p = (quint8*)data.data();
			RUasAirLogInfo info;
			info.setValuelat(*((double *)p));
			p += 8;
			info.setValuelng(*((double *)p));
			p += 8;
			info.setValuealt_Relative(*((double *)p));
			p += 8;
			result->add(info);
			data = file.read(ROFLYING_AIR_HISTORY_INFO_LENGTH);
		}
		file.close();
	}