quint16 on qbytearray - qt

i need add on firt position of qbytearray a quint16 and after read it: How can i to do it?
I have try this:
quint16 pos = 0;
QFile file(m_pathFile);
if (file.open(QFile::ReadOnly))
{
qDebug() << "el fichero existe";
m_udpSocket->bind(m_port);
QByteArray datagram;
while (!file.atEnd())
{
datagram.begin();
datagram.append(pos++);
datagram = file.read(m_blockSize);
qDebug() << "Sec" << datagram.at(0);
}
}
Thanks you very much
I got add with:
datagram.begin();
datagram.setNum(pos, 10);
datagram.append(file.read(m_blockSize));
but i don't know as read it
Thanks

Ok, first of all, that datagram.begin() is useless since it returns an iterator that you don't assign at all. If you want to insert a number in the first position of a QByteArray you can do something like:
datagram.insert(0, QString::number(pos++));
To read it, the simplest way is to use a QTextStream like this:
QTextStream str(datagram);
quint16 num;
str >> num;
Also, take a look at the docs before posting, because the Qt ones are really simple and helpful if you know how to search (and it's not that difficult, trust me).

Related

How to go from QByteArrey to a byte pointer in Qt

I want to convert my QByteArrey into a byte pointer. I found out on the internet how to go the opposite way and i found myself struggling in finding the right way to do it... So can anyone help me please?
Use data() or constData() method.
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
cout << "[" << *data << "]" << Qt::endl;
++data;
}

QString remove last characters

How to remove /Job from /home/admin/job0/Job
QString name = "/home/admin/job0/Job"
I want to remove last string after"/"
You have QString::chop() for the case when you already know how many characters to remove.
It is same as QString::remove(), just works from the back of string.
Find last slash with QString::lastIndexOf.
After that get substring with QString::left till the position of the last slash occurrence
QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf(QChar('/'));
qDebug() << name.left(pos);
This will print:
"/home/admin/job0"
You should check int pos for -1 to be sure the slash was found at all.
To include last slash in output add +1 to the founded position
qDebug() << name.left(pos+1);
Will output:
"/home/admin/job0/"
Maybe easiest to understand for later readers would probably be:
QString s("/home/admin/job0/Job");
s.truncate(s.lastIndexOf(QChar('/'));
qDebug() << s;
as the code literaly says what you intended.
You can do something like this:
QString s("/home/admin/job0/Job");
s.remove(QRegularExpression("\\/(?:.(?!\\/))+$"));
// s is "/home/admin/job0" now
If you are using Qt upper than 6 and sure that "/" constains in your word you should use QString::first(qsizetype n) const function instead QString::left(qsizetype n) const
Example:
QString url= "/home/admin/job0/Job"
QString result=url.first(lastIndexOf(QChar('/')));
If you run these code:
QElapsedTimer timer;
timer.start();
for (int j=0; j<10000000; j++)
{
QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf("/");
name.left(pos);
}
qDebug() << "left method" << timer.elapsed() << "milliseconds";
timer.start();
for (int j=0; j<10000000; j++)
{
QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf(QChar('/'));
name.first(pos);
}
qDebug() << "frist method" << timer.elapsed() << "milliseconds";
Results:
left method 10034 milliseconds
frist method 8098 milliseconds
sorry for replying to this post after 4 years, but I have (I think) the most efficient answer.
You can use
qstr.remove(0, 1); //removes the first character
qstr.remove(1, 1); //removes the last character
Thats everything you have to do, to delete characters ONE BY ONE (first or last) from a QString, until 1 character remains.

How to correctly manage a QProcess with one only argument

I'd like to monitorize how RAM memory I used for may Qt application; so, I thought about something to put inside the code.
I tried the following:
QProcess p;
p.start("ps -A");
p.waitForFinished();
QByteArray RamMem =p.readAllStandardOutput();
p.close();
quint16 pidcounter = 0;
QString pidString(RamMem);
QStringList RamMemSplit = pidString.split('\n');
quint16 RamMemSplitcounter = RamMemSplit.count();
while(pidcounter< RamMemSplitcounter)
{
if (RamMemSplit[pidcounter].contains(MyApp))
{
splitsplit = RamMemSplit[pidcounter].split(" ");
qDebug() << "Process:"<< splitsplit[10]<< "pid:"<< splitsplit[0];
}
pidcounter++;
}
In this way, I save name of running process associated to its pid;
Now, I'd like to apply another process ("pmax -x mypid), so I can obtain the RAM amount of my app:
How can I perform this? I read a QProcess requires a QStringList argument; in my case, I have only one parameter to use as argument and it's no so clear how to correctly set tyhe QProcess. The following is my idea, connected to the previous part:
QStringList listprova(splitsplit[0]);
QProcess pr;
pr.start("pmap -x", listprova);
pr.waitForFinished();
QByteArray pmapResult = pr.readAllStandardOutput();
pr.close();
QString pmapString(pmapResult);
QStringList pmapSplit = pmapString.split('\n');
quint8 pmapCounter = pmapSplit.count();
qDebug() << pmapSplit[pmapCounter]; // last line of "pmap -x [pid]" console command
You have 2 arguments, -x and the pid.
QStringList arguments;
arguments << "-x" << splitsplit[0];
QProcess pr;
pr.start("pmap", arguments);

Peek on QTextStream

I would like to peek the next characters of a QTextStream reading a QFile, in order to create an efficient tokenizer.
However, I don't find any satisfying solution to do so.
QFile f("test.txt");
f.open(QIODevice::WriteOnly);
f.write("Hello world\nHello universe\n");
f.close();
f.open(QIODevice::ReadOnly);
QTextStream s(&f);
int i = 0;
while (!s.atEnd()) {
++i;
qDebug() << "Peek" << i << s.device()->peek(3);
QString v;
s >> v;
qDebug() << "Word" << i << v;
}
Gives the following output:
Peek 1 "Hel" # it works only the first time
Word 1 "Hello"
Peek 2 ""
Word 2 "world"
Peek 3 ""
Word 3 "Hello"
Peek 4 ""
Word 4 "universe"
Peek 5 ""
Word 5 ""
I tried several implementations, also with QTextStream::pos() and QTextStream::seek(). It works better, but pos() is buggy (returns -1 when the file is too big).
Does anyone have a solution to this recurrent problem? Thank you in advance.
You peek from QIODevice, but then you read from QTextStream, that's why peek works only once. Try this:
while (!s.atEnd()) {
++i;
qDebug() << "Peek" << i << s.device()->peek(3);
QByteArray v = s.device()->readLine ();
qDebug() << "Word" << i << v;
}
Unfortunately, QIODevice does not support reading single words, so you would have to do it yourself with a combination of peak and read.
Try disable QTextStream::autoDetectUnicode. This may read device ahead to perform detection and cause your problem.
Set also a codec just in case.
Add to the logs s.device()->pos() and s.device()->bytesAvailable() to verify that.
I've check QTextStream code. It looks like it always caches as much data as possible and there is no way to disable this behavior. I was expecting that it will use peek on device, but it only reads in greedy way. Bottom line is that you can't use QTextStream and peak device at the same time.

Read exif metadata of images in Qt

In my Qt app I want to read exif data of images. QImage or QPixmap don't seem to provide such hooks.
Is there any API in Qt that allows reading exif without using external libraries like libexif?
EDIT: This is a duplicate of this
For me, the best choice was easyexif by Mayank Lahiri. You only need to add two files exif.cpp and exif.h to your project.
int main(int argc, char *argv[])
{
for (int i=1; i<argc; ++i){
QFile file(argv[i]);
if (file.open(QIODevice::ReadOnly)){
QByteArray data = file.readAll();
easyexif::EXIFInfo info;
if (int code = info.parseFrom((unsigned char *)data.data(), data.size())){
qDebug() << "Error parsing EXIF: code " << code;
continue;
}
qDebug() << "Camera model : " << info.Model.c_str();
qDebug() << "Original date/time : " << info.DateTimeOriginal.c_str();
} else
qDebug() << "Can't open file:" << argv[i];
}
return 0;
}
Try QExifImageHeader from qt extended framework. qtextended.org is not available for me? but you may search for other download mirrows.
QImageReader has a method named transformation() which is introduced in version 5.5, first you should try that.
You can also check the following link to see how it's done using Windows GDI in Qt, http://amin-ahmadi.com/2015/12/17/how-to-read-image-orientation-in-qt-using-stored-exif/

Resources