0

I am programming a tool in Qt in which I want to write binary data into a file. Everything works fine except when I am trying to write the decimal value '10' (0000 1010 in binary) into the file. in this case I get an additional byte with the value '0000 1101' in front of the other byte. It doesn't matter how much data I write in the file, as soon as I write a 10 I get another byte.

I broke it down to the following code:

#include <QCoreApplication>
#include <QFile>
#include <iostream>
#include <QString>
#include <QDataStream>

int main(int argc, char *argv[])
{
 QCoreApplication a(argc, argv);

 QString SavePath;
 SavePath = qApp->applicationDirPath();
 SavePath.append("/test.bin");

 QFile file(SavePath.toLocal8Bit().constData());
 if (file.exists())
     file.remove();
 if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
 {
    std::cout << "Kann Datei zum Speichern der TP-Daten nicht erstellen." << std::endl;
    std::cout << SavePath.toLocal8Bit().constData() << std::endl;
    return -1;
 }


 QDataStream out(&file);
 out.setVersion(QDataStream::Qt_4_3);
 out.setByteOrder(QDataStream::LittleEndian);
 out << qint32(10);

 int test=10;
 out.writeRawData((char*)&test,4 );

 file.write((char*)&test);

 return 1;
}

The output in my file is:

0d 0a 00 00 00 0d 0a 00 00 00 0d 0a

the three 0x0d bytes are unwanted. I don't get them while writing a '9' or an '11' to the file. I am running out of ideas. Can anyone tell me what I am doing wrong?

Mech Mobo
  • 3
  • 1
  • The [`QFile::write`](http://doc.qt.io/qt-5/qiodevice.html#write-1) overload you're calling expects a null terminated character array. Your code will exhibit undefined behaviour. – G.M. Nov 22 '16 at 12:55
  • Thanks for your answer! – Mech Mobo Nov 22 '16 at 13:17

2 Answers2

3

If you want binary file, remove QIODevice::Text flag, dude. Otherwise it add CR(0x0D) symbol to LF(0x0A) symbol in Windows.

Edward
  • 149
  • 7
0

Just solved the problem in the Qt Forum:

by adding the QIODevice::Text Flag in the open function I made it a text file. After deleting this everything works fine.

Mech Mobo
  • 3
  • 1