elachere
elachere

Reputation: 815

QTextStream write data in file

I'm learning QtCreator and having troubles writing data in file. Here's some code :

char    *str;
int     i = 1;
QFile outFile("path/to/file/out.txt");
outFile.open(QIODevice::ReadWrite);
QTextStream out(&outFile);

while (i < rows * 2) {
    str = dynamic_cast<QLineEdit *>(this->getItem(i))->text().toLocal8Bit().data();
    std::cout << str << std::endl;
    out << str << "\n";
    i += 2;
}

getItem returns a QWidget * from a QFormLayout filled with QLineEdit (that explains the dynamic cast). Anyway, when I pass str into std::cout it works fine, the data is printed, but when I pass str into out, it writes only the first char of str in the file.
I don't get what I'm doing wrong, I really would appreciate any tips.

Upvotes: 0

Views: 2277

Answers (1)

Simon Kraemer
Simon Kraemer

Reputation: 5680

This line is a problem: str = dynamic_cast<QLineEdit *>(this->getItem(i))->text().toLocal8Bit().data();

dynamic_cast<QLineEdit *>(this->getItem(i))-> is OK
->text() creates a temporary QString
.toLocal8Bit() creates a temporary QByteArray
.data() returns a pointer to the internal data of the QByteArray

As soon as the line is passed the QByteArray will be destroyed and you have a dangling pointer. str points to invalid data.

Everything you do with this pointer afterwards (except letting it point to somewhere else) is undefined behaviour.

Try to use something like this:

int     i = 1;
QFile outFile("path/to/file/out.txt");
outFile.open(QIODevice::ReadWrite);
QTextStream out(&outFile);
while (i < rows * 2) 
{
    QLineEdit* lineEdit = dynamic_cast<QLineEdit *>(this->getItem(i));
    if (lineEdit)
    {
        QByteArray str = lineEdit->text().toLocal8Bit();
        std::cout << str.data() << std::endl;
        out << str.data() << "\n";
        i += 2;
    }
    else
    {
        std::cerr << "Item at " << i << " is no QLineEdit*" << std::endl;
    }
}
out.close();

Also please check whether QFile is actually open and whether QTextStream reports some errors when writing.

Upvotes: 1

Related Questions