QFile / QTextStream



  • Hi everyone,

    I want to do a very simple thing but I can't do it ...
    I have a log file saved in some place (D://test.txt), I use a QTextStream to write text in it.

    m_file.setFileName(fileName);
    if (m_file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
    	m_streamFile.setDevice(&m_file);
    }
    
    ...
    
    m_streamFile << msg;
    endl(m_streamFile);
    

    I create a menu to change its location.
    I just replace the file name:

    m_file.rename(dirName + "/" + fileName + ".txt");
    

    But when new log messages appear, they are not written in the new file ...

    Any idea ?

    Thanks !



  • before m_streamFile << msg; could you put Q_ASSERT(m_streamFile.device()->isOpen()); ?



  • The API of QFile::rename(...) says:
    "The file is closed before it is renamed."
    So you have to open the file again after renaming...



  • @VRonin said:

    Q_ASSERT(m_streamFile.device()->isOpen());

    You are right, the file is closed. But if I open it, the previous file content is cleared ...

    m_file.rename(newFileName);
    if (m_file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
    	m_streamFile.setDevice(&m_file);
    }
    


  • @ClaraCaste Try to open in append mode, otherwise the file will be truncated:
    if (m_file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))



  • It works !
    It seems obvious ...
    Thank you very much !


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.