Ali
Ali

Reputation: 171

Write binary data in QT '\n' 0x10->0x0d,0x010

I work on project that involved writing binary data, I use QString for storing line and then save it on hard by Qfile

 data.append(QChar(10));

and I set encoding to "ISO-8859-1", anyway when the data equal to 10 I as showed above, the saved data is 0x0d,0x0a I find the problem source ,10='\n' and Qt change it to '\n\r' so it happened.

How can I fix it?

Upvotes: 0

Views: 1531

Answers (2)

Samuel Harmer
Samuel Harmer

Reputation: 4412

Your question and answer are poor for several reasons. Here are the problems I've spotted immediately:

  1. If you're really writing binary data, do not use strings. For reasons why, read and understand the following pages:
    The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
    QString class documentation
    QChar class documentation
  2. The problem of getting "\r\n" stems from issue #1 but you would not find this problem on a Linux based operating system.
  3. You haven't included what type the data object is in your question, which means we don't really know what data.append(...) is doing. Make sure your posts include a short, self contained, correct (compilable), example. Furthermore, in the answer you posted, there is no mention of this data object.
  4. What is a byte? It's not part of C++ or Qt and those are the only two tags you've given us to go on.
  5. In your answer you've flipped to using C++ streams instead. Be wary of doing this as you bypass a lot of the 'safety' features included by using Qt streams. If you're already using Qt, use it for as much as you can as it's designed to work together.

Upvotes: 1

Ali
Ali

Reputation: 171

I found the reason, because the QFile object that I had created is in Text mode so when QFile want to write file it changes /n to /r/n the code below is the previous code that have problem in binary because of existence of QIODevice::Text

QFile myfile;
myfile.setFileName("build/Data.bin");
if(!myfile.open(QIODevice::WriteOnly|QIODevice::Text))
    return;

for binary mode simply we can omite QIODevice::Text so the second line change to

if(!myfile.open(QIODevice::WriteOnly))

at first I think this is the Qt's bug, and try to use ofstream to write file, the same thing happened with ofstream, and finally writing binary code with ofstream is showed below the point is std::ios_base::binary

ofstream file;
file.open ("example.txt", std::ios_base::out | std::ios_base::binary);
file << (byte)10;
file.close();

Upvotes: 0

Related Questions