简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM