Question

I want to write a binary file with QDataStream. The problem is with the code below, when I write my_string = "13", I read 0 ; when my_string is not equal to "13" ("12", "14", "20", ...), I read the real value (12, 14, 20, ...). Does anybody know why I have this problem just with the number 13.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //open the file to write
    QFile file1("test");
    if (!file1.open(QIODevice::WriteOnly | QIODevice::Text))
        return;
    QDataStream stream1(&file1);
    QString my_string = "13";

    qint8 val8 = my_string.toInt();
    stream1 << val8;

    file1.close();


    //open the file to read
    QFile file2("test");
    file2.open(QIODevice::ReadOnly | QIODevice::Text);

    QDataStream stream2(&file2);

    qint8 val2;
    stream2>> val2;

    QListWidgetItem *item = new QListWidgetItem;
    item->setText(QString::number(val2));
    ui->listWidget->addItem(item);

    file2.close();
}
Était-ce utile?

La solution

You opened the file in text mode and you write binary value. The character with code 13 (0xD) is a newline. Open the file in binary mode by removing QIODevice::Text, it should start working.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top