QDataStream 没有按预期工作

QDataStream not working as expected

我正在 QDataStream 中存储一些数据并立即获取数据,但在检索时计数显示为零。代码看起来不错,但出现意外行为

//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;
    } 
}
   file.open(QFile::ReadWrite);
   file.close(); <--- HERE

   QDataStream dStream(&file);

您在打开文件后立即将其关闭,因此基本上您使用的是无效的文件描述符,它不会起作用。完成后将 file.close() 放在代码的末尾。