QTemporaryFile and QTextStream: No content written



  • Hi all. This one is confusing me, so I'm asking for some input.

    I have a method intended to create and populate a temporary file:

    @QTemporaryFile* JSHelper::getTemporaryFile(const QString& content) {
    QTemporaryFile* tempFile = new QTemporaryFile("tmp.js");
    tempFile->setAutoRemove(false);

    if (tempFile->open())
    { 
        QTextStream out(tempFile);
        out << content << "\n";
        tempFile->close();
    }
    else
        qDebug() << "JSHelper::getTemporaryFile&#40;&#41;: Could not open temp file";
    
    return tempFile;
    

    }@

    The problem is, the content of the populated file is always empty (at least on Windows XP). If I change the file object type to QFile, and open() with QIODevice::WriteOnly | QIODevice::Text (QTemporaryFile::open() takes no arguments), everything works great.

    Does anyone have any clue of why I can't write content to a QTemporaryFile like I'm trying to do? Mostly out of curiosity, as I will just use a regular file for now.



  • Hi,
    First of all, You might have a memory leak on your hands here.
    When you return the QTemporaraFile pointer to the caller, the allocated memory on the heap might get deleted in the destructor of the tempFile variable when going out of scope. You might say that the data is still there in the debugger, but that might just be the old, not yet overwritten, data! When other threads or events etc allocate new memory, you even get weird data in that part of the memory, but you still think you 'own' the piece of Heap in your QTemporaryFile pointer from the caller! A good rule is to never return a pointer to allocated memory outside the scope of this memory.
    That might explain what happens? The rest look workable code to me.
    Greetz



  • I don't see this as a reasonable explanation. As I wrote, if I replace QTemporaryFile with QFile, it works. Also, I don't see anything going out of scope here, apart from the stack allocated objects . I'm allocating on the heap. I open a file, write to it, then close it, all in the same scope. In my world, whatever you do to any temporary objects from here, should not matter. The file is closed.

    The thing is, I'm not even interested in using the file object afterwards - only the file name, to pass to QProcess. The file name is ok, the file exists. But the file itself is empty when using QTemporaryfile like this.

    Could it be that QTemporaryfile is not happy about text content?



  • I wrote some skeleton code around your method and it seems to work as expected with Qt5.2, Win7.
    I pass to it the content of a QTextEdit->toPlainText() and get the expected text in the temporary file.
    Could just be an XP thing ?



  • Hm, it could be. In my own case, I just use a normal QFile instead. Problem solved.


Log in to reply
 

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