[英]Deleting currently loaded files using Qt on Windows
我正在尝试删除在卸载过程中由应用程序创建的所有临时文件。 我使用以下代码:
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;
}
我的应用程序崩溃了。 我认为这是由于所执行的操作缺少Windows dll导致的。 还有其他方法可以单独使用Qt执行相同的操作吗?
Roku已经告诉您使用QString和wchar_t *进行操作的问题。 请参阅文档: QString类参考,方法toWCharArray :
int QString::toWCharArray ( wchar_t * array ) const
用此QString对象中包含的数据填充数组。 在wchar_t为2字节宽的平台(例如Windows)上,该数组在utf16中进行编码;在wchar_t为4字节宽的平台(大多数Unix系统)上,在ucs4中进行编码。
数组必须由调用方分配,并包含足够的空间来容纳完整的字符串 (以与字符串相同的长度分配数组总是足够的)。
返回数组中字符串的实际长度。
如果您只是在寻找一种使用Qt删除文件的方法,请使用QFile::remove
:
QFile file(fileNameStr);
file.remove(); // Returns a bool; true if successful
如果您想让Qt为您管理一个临时文件的整个生命周期,请查看QTemporaryFile
:
QTemporaryFile tempFile(fileName);
if (tempFile.open())
{
// Do stuff with file here
}
// When tempFile falls out of scope, it is automatically deleted.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.