-4

i have a QByteArray variable like this:

QByteArray read= port->readAll();

now i want convert read to Array for write binary file like this:

int b[] = {}; // lengh of array is port->readAll() size
QFile myFile("e:/test/test.dat");
if(!myFile.open(QIODevice::WriteOnly))return;
myFile.write((char*)b,sizeof(int));
myFile.flush();
myFile.close();
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • 1
    Why can't you use `data()` for that - do you need it to outlive the `QByteArray`, or is there another reason? BTW, I really wouldn't use the name `read` for a variable - too similar to popular library or system call names. – Toby Speight Nov 22 '18 at 16:34
  • my problem is convert QByteArray to Array. – jocker fantom Nov 22 '18 at 16:39
  • 2
    Why do you need to, given that you can access the contents of the `QByteArray` for purposes such as the code you show? It's not at all obvious what you're trying to do that's not achieved by `myFile.write(read.data(), sizeof (int))`. Or, if you meant to write the whole array, `myFile.write(read.data(), read.size())` or equivalently, just `myFile.write(read)`. – Toby Speight Nov 22 '18 at 16:43
  • i hav to read all data from modem: QByteArray read= port->readAll(); and write it – jocker fantom Nov 22 '18 at 16:51
  • So why can't you just pass the `QByteArray` to `QFile::write()` as I've shown? It's still unclear why that won't work for you. – Toby Speight Nov 22 '18 at 16:56
  • @jockerfantom You seem to be having an [xy problem](http://xyproblem.info/). QFile is [perfectly capable of handling QByteArray](http://doc.qt.io/qt-5/qiodevice.html#write-2)s. – TrebledJ Nov 22 '18 at 16:59

1 Answers1

0

No need to create int[] b = ..etc Just use either the method QByteArray::data():

QFile file(...);
QByteArray byteArray = ...
...
file.write(byteArray.data(), byteArray.size());

Or you can set the QByteArray's object directly to file.write():

QFile file(...);
QByteArray byteArray = ...;

file.write(byteArray);
Alexander Chernin
  • 446
  • 2
  • 8
  • 17