[英]Delete files and folders by date using SHFileOperation
I'm trying to write a program that will delete a set of files/folders that are matching a specific naming pattern (wild cards) based on their dates using the windows API 我正在尝试编写一个程序,该程序将使用Windows API根据日期删除一组与特定命名模式(通配符)匹配的文件/文件夹
...
SHFILEOPSTRUCT shFileOpStruct = {
.hwnd = NULL,
.wFunc = processByDate->op,
.pTo = NULL,
.fFlags = FOF_NOCONFIRMATION | FOF_SILENT
};
buildReferenceDate( &refTime, processByDate->nDays );
hFind = FindFirstFile( processByDate->srcFileName, &findFileData );
errorCode = GetLastError();
while ( errorCode == ERROR_SUCCESS ) {
LONG res = CompareFileTime( &refTime, &findFileData.ftCreationTime );
if ( (processByDate->nDays ^ res) > 0 ) {
sprintf( strrchr(processByDate->srcFileName, '\\') + 1, "%s%c",
findFileData.cFileName, '\0');
shFileOpStruct.pFrom = processByDate->srcFileName;
fprintf( stdout, "\n%s\n", shFileOpStruct.pFrom);
fprintf( stdout, "\n0x%x\n", SHFileOperation( &shFileOpStruct ));
}
FindNextFile( hFind, &findFileData );
errorCode = GetLastError();
}
if ( errorCode != ERROR_NO_MORE_FILES )
displayError ( stdout, errorCode );
...
Only the first matching file is deleted, because FindNextFile terminates with "The handle is invalid." 仅删除第一个匹配的文件,因为FindNextFile终止于“句柄无效”。 apparently SHFileOperation somehow invalidates the file handle (or at least so I suppose).
显然SHFileOperation以某种方式使文件句柄无效(或者至少我想如此)。 The only solution I can think of is to save the name of the matching files/folders and delete them one by one.
我能想到的唯一解决方案是保存匹配文件/文件夹的名称,然后逐个删除它们。 Is there any other simpler solution?
还有其他更简单的解决方案吗?
Thanks 谢谢
FindNextFile( hFind, &findFileData );
errorCode = GetLastError();
That's wrong. 错了 Only call GetLastError() when you get a FALSE return from FindNextFile().
当您从FindNextFile()获得FALSE返回值时, 仅调用GetLastError()。 Fix:
固定:
if (!FindNextFile( hFind, &findFileData ) {
errorCode = GetLastError();
}
The thread's last error code is not set when a function succeeds. 函数成功时未设置线程的最后一个错误代码。 Instead of calling
GetLastError
, you have to check the return value of FindNextFile
. 不必调用
GetLastError
,而必须检查FindNextFile
的返回值。
If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file or directory found.
如果函数成功,则返回值为非零,并且lpFindFileData参数包含有关找到的下一个文件或目录的信息。
If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate.
如果函数失败,则返回值为零,并且lpFindFileData的内容不确定。
FindNextFile function FindNextFile函数
The loop should look like this: 循环应如下所示:
HANDLE handle(FindFirstFile(...));
if (handle != INVALID_HANDLE_VALUE)
{
do
{
// filter files here
}
while (FindNextFile(handle, ...));
FindClose(handle);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.