Does QBuffer write data in system dependent byte order? - qt

The documentation says that QDataStream writes data in system independent way, but it says nothing about QBuffer. I develop a program that saves data in a file like this:
QByteArray a;
QBuffer b(&a);
b.open(QIODevide::WriteOnly);
quint32 x = 1;
b.write((char*)&x, sizeof(x));
b.close();
QFile f(...);
f.open(QIODevide::WriteOnly);
f.write(a.constData(), a.size());
f.close();
, and i want this file can be read in any other OS (win, linux, Mac OS). Will this code work or i must use QDataStream instead?

The QBuffer documentation says :
The QBuffer class provides a QIODevice interface for a QByteArray.
ie it is only a QByteArray underneath. On the other hand a QByteArray is portable because as long as you see the data as an array of byte and write one byte at a time you are fine. Your code will work:
When you say
I want this file to be read in any other OS
Is your file used by your program only or will it be used by other applications in the system? QDataStream provides nicer functions for I\O and you may be still able to take advantage of it.
It will be platform specific. x representation in memory depend on the endianess.It doesn't occur in the QBuffer, but when you do :
b.write((char*)&x, sizeof(x));
If you are on machines of different endianess, you will obtain different values for the resulting array by doing
char* data = &x;
qDebug()<< data[0];
qDebug()<< data[1];
qDebug()<< data[2];
qDebug()<< data[3];
Take a look at the source code of QDataStream operator
QDataStream &QDataStream::operator<<(qint32 i){
CHECK_STREAM_WRITE_PRECOND(*this)
if (!noswap) {
i = qbswap(i);
}
if (dev->write((char *)&i, sizeof(qint32)) != sizeof(qint32))
q_status = WriteFailed;
return *this;
}

Related

Qt logical error during getting user's input from terminal via getline function and writing it into a file

Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it. I face with logical error during Runtime; whatever I as user write doesn't type into the output terminal and it doesn't succeed more steps. Apparently fwrite function with this feature in the libraries exists, but I want to write my own code differently this way. I think I must have neglected a point. Here's the code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <String>
#include <cstdlib>
using namespace std;
void wFile(QString Filename)
{
QFile mFile(Filename);
QTextStream str(&mFile);
qDebug() << "what do you want to write in the desired file: ";
istream& getline (istream& is, string& str);
if (!mFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
mFile.flush();
mFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename ="P:/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
Spoiler alarm: At the very end of this answer, there is a very simple recommendation for a fix.
What OP did
Concerning istream& getline (istream& is, string& str); in wFile(QString Filename):
This declares function getline() in function wFile().
This is a valid declaration concerning C++.
Concerning the sample code, I missed the respective headers. IMHO,
#include <istream> and
#include <string>
are required to make this compiling.
However, it is possible that the existing #includes include them indirectly. So, OP's code may even compile without them.
Declaring functions, which are not used as well as re-declaring functions which are already declared is somehow useless but not wrong.
To demonstrate this, I made a small sample:
#include <cstdio>
#include <istream>
#include <string>
void func()
{
puts("in func()\n");
std::istream& getline(std::istream&, std::string&);
// Even duplicated prototyping is accepted without complaints:
std::istream& getline(std::istream&, std::string&);
}
int main ()
{
func();
return 0;
}
compiles and runs perfectly.
Output:
in func()
Live Demo on coliru
What OP (probably) wanted
Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it.
This sounds a bit confusing to me. std::getline(std::cin, ) can be used to read user input from console. May be, it's a bit bad wording only.
Assuming, the OP wanted to read input from console, obviously, declaring a function is not sufficient – it must be called to become effective:
#include <iostream>
void func()
{
std::cout << "Enter file name: ";
std::string fileName; std::getline(std::cin, fileName);
std::cout << "Got file name '" << fileName << "'\n");
}
int main ()
{
func();
return 0;
}
Output:
Enter file name: test.txt↵
Got file name 'test.txt'
Live Demo on coliru
C++ std vs. Qt
Qt is undoubtly built on top of the C++ std library. However, though it's possible it is not recommended to mix both APIs when it can be prevented (or there aren't specific reasons to do so).
Both, Qt and C++ std, are a possibility to write portable software.
Qt covers a lot of things which are provided in the std library as well but a lot of other things additionally which are not or not yet part of std. In some cases, the Qt is a bit less generic but more convenient though this is my personal opinion. IMHO, the following explains how I came to this:
std::string vs. QString
std::string stores a sequence of chars. The meaning of chars when exposed as glyph (e.g. printing on console or displaying in a window) depends on the encoding which is used in this exposing. There are lot of encodings which interprete the numbers in the chars in distinct ways.
Example:
std::string text = "\xc3\xbc";
Decoded/displayed with
Windows-1252: ü
UTF-8: ü
Based on character type of std::string, it is not possible to determine the encoding. Hence, an additional hint must be provided to decode this properly.
(AFAIK, it is similar for std::wstring and wchar_t.)
QString stores a sequence of Unicode characters. So, one universal encoding was chosen by design to mitigate the "encoding hell".
As long as the program operates on QString, no encoding issues should be expected. The same is true when combining QString with other functions of Qt. However, it becomes a bit more complicated when "leaving the Qt universe" – e.g. storing contents of a std::string to QString.
This is the point where the programmer has to provide the additional hint for the encoding of the contents in std::string. QString provides a lot of from...() and to...() methods which can be used to re-encode contents but the application programmer is still responsible to chose the right one.
Assuming that the intended contents of text should have been the ü (i.e. UTF-8 encoding), this can be converted to QString (and back) by:
// std::string (UTF-8) -> QString
std::string text = "\xc3\xbc";
QString qText = QString::fromUtf8(text.c_str());
// QString -> std::string (UTF-8)
std::string text2 = qText.toUtf8();
This has to be considered when input from std::cin shall be passed to QString:
std::cout << "Enter file name: ";
std::string input; std::getline(std::cin, input);
QString qFileName = QString::fromLocal8Bit(input);
And even now, the code contains a little flaw – the locale of std::cin might have changed with std::ios::imbue(). I must admit that I cannot say much more about this. (In daily work, I try to prevent this topic at all e.g. by not relying on Console input which I consider especially critical on Windows – the OS on which we usually deploy to customers.)
Instead, a last note about OP's code:
How to fix it
Remembering my above recommendation (not to mix std and Qt if not necessary), this can be done in Qt exclusively:
QTextStream qtin(stdin);
qtin.readline();
I must admit that I never did it by myself but found this in the Qt forum: Re: stdin reading.

Is this code send hex data in correct way in Qt C++?

I am new to Qt.I am working on finger print madoule with this document. I want to send my data to serial port in this format:
I wrote my code in this format, but I think my data has mistake, because this code turn on the LED in some device:
QByteArray ba;
ba.resize(24);
ba[0]=0x55;
ba[1]=0xAA;
ba[2]=0x24;
ba[3]=0x01;
ba[4]=0x01;
ba[5]=0x00;
ba[6]=0x00;
ba[7]=0x00;
ba[8]=0x00;
ba[9]=0x00;
ba[10]=0x00;
ba[11]=0x00;
ba[12]=0x00;
ba[13]=0x00;
ba[14]=0x00;
ba[15]=0x00;
ba[16]=0x00;
ba[17]=0x00;
ba[18]=0x00;
ba[19]=0x00;
ba[20]=0x00;
ba[21]=0x00;
ba[22]=0x27;
ba[23]=0x01;
p->writedata(ba);
Is this data correct?
You're just copying a drawing into code. It won't work without understanding what the drawing means. You seem to miss that:
The LEN field seems to be a little-endian integer that gives the number of bytes in the DATA field - perhaps it's the number of bytes that carry useful information if the packet has a fixed size.
The CKS field seems to be a checksum of some sort. You need to calculate it based on the contents of the packet. The protocol documentation should indicate whether it's across the entire packet or not, and how to compute the value.
It seems like you are talking to a fingerprint identification module like FPM-1502, SM-12, ADST11SD300/310 or similar. If so, then you could obtain a valid command packet as follows:
QByteArray cmdPacket(quint16 cmd, const char *data, int size) {
Q_ASSERT(size <= 16);
QByteArray result(24, '\0');
QDataStream s(&result, QIODevice::WriteOnly);
s.setByteOrder(QDataStream::LittleEndian);
s << quint16(0xAA55) << cmd << quint16(size);
s.writeRawData(data, size);
s.skipRawData(22 - s.device()->pos());
quint16 sum = 0;
for (int i = 0; i < 22; ++i)
sum += result[i];
s << sum;
qDebug() << result.toHex();
return result;
}
QByteArray cmdPacket(quint16 cmd, const QByteArray& data) {
return cmdPacket(cmd, data.data(), data.size());
}
The command packet to turn the sensor led on/off can be obtained as follows:
QByteArray cmdSensorLed(bool on) {
char data[2] = {'\0', '\0'};
if (on) data[0] = 1;
return cmdPacket(0x124, data, sizeof(data));
}

How to 'steal' data from QByteArray without copy

Is it possible to take pointer to QByteArray's internal T* data and destroy QByteArray itself so that the pointer remains unreleased? I would like to use it in the something similar to the following scenario:
const char* File::readAllBytes(const String& path, u64& outCount) {
QFile file(*static_cast<QString*>(path.internal()));
outCount = static_cast<u64>(file.size());
if (!file.open(QIODevice::ReadOnly)) gException("Failed to open file");
const QByteArray array = file.readAll();
return array.steal();
}
No, you can't steal QByteArray's pointer unless it has been constructed with QByteArray::fromRawData, which is not the case. However you can create char array manually and read data from file to it using QFile::read(char * data, qint64 maxSize). You will then decide where to pass the pointer and when to delete[] it.
Note that this is not considered good practice. You should use managed allocations whenever you can, and Qt provides enough to cover most of possible use cases. You should not do this unless you're trying to do something really low-level.
Note that many of Qt classes, including QString and QByteArray, use copy-on-write strategy, so you generally should not be afraid of copying them and passing them to another context.
No, but you can easily sidestep the problem by not using QByteArray:
const char* File::readAllBytes(const String& path, u64& outCount) {
QFile file(*static_cast<QString*>(path.internal()));
if (!file.open(QIODevice::ReadOnly)) return nullptr;
auto N = file.bytesAvailable();
char *data = malloc(N);
outCount = file.read(data, N);
return data;
}
The solution above also assumes that the consumer of your data is aware of the need to free the data.
Alas, the manual memory management called for with such an API is a bad idea. If you wish not to use Qt classes in your API, you should be using std::vector<char> instead:
std::vector<char> File::readAllBytes(const String& path) {
std::vector<char> result;
QFile file(*static_cast<QString*>(path.internal()));
if (!file.open(QIODevice::ReadOnly)) return result;
result.resize(file.bytesAvailable());
auto count = file.read(result.data(), result.size());
result.resize(count);
return result;
}
I smell that String is some sort of a framework-independent string wrapper. Perhaps you could settle on std::u16string to carry the same UTF16 data as QString would.

How to convert double* data to const char* or QByteArray efficiently

I am trying to use the network programming APIs in Qt in my project. One part of my code requires me to convert double* data to QByteArray or a const char*.
I searched through the stackoverflow questions and could find many people suggesting this code :
QByteArray array(reinterpret_cast<const char*>(data), sizeof(double));
or, for an array of double :
QByteArray::fromRawData(reinterpret_cast<const char*>(data),s*sizeof(double));
When I use them in my function, It does notgive me the desired result. The output seems to be random characters.
Please Suggest an efficient way to implement it in Qt. Thank you very much for your time.
Regards
Alok
If you just need to encode and decode a double into a byte array, this works:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray(reinterpret_cast<const char*>(&value), sizeof(double));
// Decode the value
double outValue;
// Copy the data from the byte array into the double
memcpy(&outValue, byteArray.data(), sizeof(double));
printf("%f", outValue);
However, that is not the best way to send data over the network, as it will depend on the platform specifics of how the machines encode the double type. I would recommend you look at the QDataStream class, which allows you to do this:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << value;
// Decode the value
double outValue;
QDataStream readStream(&byteArray, QIODevice::ReadOnly);
readStream >> outValue;
printf("%f", outValue);
This is now platform independent, and the stream operators make it very convenient and easy to read.
Assuming that you want to create a human readable string:
double d = 3.141459;
QString s = QString::number(d); // method has options for format and precision, see docs
or if you need localization where locale is a QLocale object:
s = locale.toString(d); // method has options for format and precision, see docs
You can easily convert the string into a QByteArray using s.toUtf8() or s.toLatin1() if really necessary. If speed is important there also is:
QByteArray ba = QByteArray::number(d); // method has options for format and precision, see docs

Serial port communication in Qt

I am new to Qt and need to prepare a project to send hex commands from rs232.
QString line contains 64bit binary data which i have to convert into hexadecimal and send it through rs232 .
QString a=ui->comboBox->currentText();
QString s1;
s1="./calc "+a;
QProcess p1;
p1.start(s1);
p1.waitForFinished(-1);
QString line ;
//read
QFile file("TeleOutput.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in (&file);
line = in.readAll();
ui->plainTextEdit->setPlainText(line);
So, how to convert 64 bit binary data in QString line to hexadecimal value and transfer it through rs232?
First of all - you should really use QtSerialPort
Second of all - QString is a class, which works with actual string. QByteArray works with raw data. When you write QString line = in.readAll(); it implicitly calls QString(const QByteArray &ba), which uses QString::fromAscii.
Last of all, if you want to process 64bit integers, you should do something like this:
quint64 d;
QDataStream stream(&file);
while (!stream.atEnd())
{
stream >> d;
process(d);
}
Update
Quote:
My problem is that in plainTextEdit
"1111110101000101010101010101010101010101010101010101010......." 64
bit data is populated , i need to convert this data into hex and send it through rs232
Solution:
QString binData = plainTextEdit.toPlainText();
QByteArray result;
while (binData.size() >= 64)
{
quint64 d;
QString dataPiece = binData.left(64);
binData.remove(0, 64);
d = dataPiece.toULongLong(0, 2);
result += QByteArray::number(d);
}
_com->write(result);
_com->flush();
Where _com is a pointer to QtSerialPort, with all parameters set and opened without errors.

Resources