qtqt4qt5qdatastream

QDataStream not working as expected


I am storing some data in QDataStream and immediately taking the data, but the count is showing zero while retriving. code looks fine but unexpected behaviour

//Overloading
QDataStream& operator<< (QDataStream& writeTO, const CascadeJobInfo& data)
{
    writeTO << data.m_infoJobType << data.m_connectionName << data.m_submitJobId << data.m_submitJobStat;
    return writeTO;
}

QDataStream& operator>> (QDataStream& readIn, CascadeJobInfo& data)
{
    readIn >> data.m_infoJobType >> data.m_connectionName >> data.m_submitJobId >> data.m_submitJobStat;
    return readIn;
}

void Fun()
{
        // Code Starts here
    projectFileName = /*Path to folder*/
    QFile file(projectFileName);
    file.open(QFile::ReadWrite);
    file.close();

    QDataStream dStream(&file);
    int jobLstCount = /*Get the Count, assume 4*/
    dStream << jobLstCount;

    for(int i = 0; i < jobLstCount; i++)
    {
    JobInfo.m_infoJobType = jobFlowItem->getJobType();
    JobInfo.m_connectionName = submitItem->connectionName();
    JobInfo.m_submitJobId = submitItem->jobID();
    JobInfo.m_submitJobStat = submitItem->jobState();
        // All valid data stored here
    }

    file.close();

    QDataStream dStreamOut(&file);
    dStreamOut >> jobLstCount; /*Count returns zero here insted of 4*/
    CascadeJobInfo jobInfo;
    // Why jobLstCount is getting zero here
    for(int i = 0 ; i < jobLstCount ; i++)
    {
    dStreamOut >> jobInfo;
    } 
}

Solution

  •    file.open(QFile::ReadWrite);
       file.close(); <--- HERE
    
       QDataStream dStream(&file);
    

    You are closing the file as soon as you open it, so basically you are working with an invalid file descriptor which won't work. Put file.close() at the end of the code when you are done.