qtqt5qdatastream

QDataStream not working as well and return error with reusing


I am storing some data in QDataStream and immediately taking the data

bool M_FILEMANAGER::readFromDataFile(QString& fileName,RADARBEAMPATTERN *radbeam)
{
// for reading from file sequence .....
QFile fin(m_folderPath +"/"+ fileName);
if (fin.open(QIODevice::ReadOnly)) {
    QDataStream in(&fin);
    in.device()->startTransaction();
    in >> radbeam->nPoints;
    qDebug()<<"nPoints : "<<radbeam->nPoints;
    fin.close();
    return true;
}else{
    return false;
}
}

it works fine for one use but when i reuse this function i get error segmentation fault. thanks in advance.


Solution

  • 1) Strange use of QIODevice::startTransaction(). Did you mean to use QDataStream:startTransaction()? You shouldn't need that at all, but if you meant to use it to check for "valid" (complete) data in the file, do it properly (although this is typically used with async devices like sockets):

    int nPoints;  // temp variable to hold data, assuming radbeam->nPoints is an int
    QDataStream in(&fin);
    in.startTransaction();
    in >> nPoints;
    if (in.commitTransaction() && radbeam != nullptr)
        radbeam->nPoints = nPoints;
    fin.close();
    

    2) Segfault is most likely due to radbeam pointer (eg. being null), but possibly if you're trying to read corrupted data directly into the member variable nPoints. Impossible to determine cause w/out MCVE.