简体   繁体   中英

Deleting currently loaded files using Qt on Windows

I am trying to delete all the temporary files created by my application during uninstall. I use the following code:

 bool DeleteFileNow( QString filenameStr )
    {
        wchar_t* filename;
        filenameStr.toWCharArray(filename);

        QFileInfo info(filenameStr);

        // don't do anything if the file doesn't exist!
        if (!info.exists())
            return false;

        // determine the path in which to store the temp filename
        wchar_t* path;
        info.absolutePath().toWCharArray(path);

        TRACE( "Generating temporary name" );
        // generate a guaranteed to be unique temporary filename to house the pending delete
        wchar_t tempname[MAX_PATH];
        if (!GetTempFileNameW(path, L".xX", 0, tempname))
            return false;

        TRACE( "Moving real file name to dummy" );
        // move the real file to the dummy filename
        if (!MoveFileExW(filename, tempname, MOVEFILE_REPLACE_EXISTING))
        {
            // clean up the temp file
            DeleteFileW(tempname);
            return false;
        }

         TRACE( "Queueing the OS" );
        // queue the deletion (the OS will delete it when all handles (ours or other processes) close)
        return DeleteFileW(tempname) != FALSE;
    }

My application is crashing. I think its due to some missing windows dll for the operations performed. Is there any other way to perform the same operation using Qt alone?

Roku have already told your problem in manipulating with QString and wchar_t*. See the documentation: QString Class Reference, method toWCharArray :

int QString::toWCharArray ( wchar_t * array ) const

Fills the array with the data contained in this QString object. The array is encoded in utf16 on platforms where wchar_t is 2 bytes wide (eg windows) and in ucs4 on platforms where wchar_t is 4 bytes wide (most Unix systems).

array has to be allocated by the caller and contain enough space to hold the complete string (allocating the array with the same length as the string is always sufficient).

returns the actual length of the string in array.

If you are simply looking for a way to remove a file using Qt, use QFile::remove :

QFile file(fileNameStr);
file.remove(); // Returns a bool; true if successful

If you want Qt to manage the entire life cycle of a temporary file for you, take a look at QTemporaryFile :

QTemporaryFile tempFile(fileName);
if (tempFile.open())
{
   // Do stuff with file here
}

// When tempFile falls out of scope, it is automatically deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM