- #include
- #include
-
- int main() {
- // 删除Windows临时目录下的所有文件和子目录
- system("del /s /q %temp%\\*.*");
- system("for /d %x in (%temp%\\*) do @rd /s /q \"%x\"");
-
- printf("Temporary files and directories deleted successfully.\n");
-
- return 0;
- }
system() 调用仍然是删除临时目录下的所有文件。system() 调用使用了一个 for 循环配合 rd 命令来删除所有子目录:
for /d %x in (%temp%\\*) do @rd /s /q "%x" 这行命令的作用是遍历 %temp% 目录下的每一个子目录,并使用 rd(remove directory)命令来递归地删除这些目录及其包含的所有内容。/d 参数用于循环遍历所有子目录。@rd /s /q 用于静默模式递归删除目录。其中,/s 是递归删除目录的内容,/q 是不提示用户确认。----------
DeleteDirectoryContents 函数使用 Windows API 遍历指定目录下的所有文件和子目录。FindFirstFile 和 FindNextFile 遍历文件,DeleteFile 删除文件,RemoveDirectory 删除目录。system() 函数,减少了由于外部命令注入带来的安全风险。- #include
- #include
-
- void DeleteDirectoryContents(const char *sDir) {
- WIN32_FIND_DATA fdFile;
- HANDLE hFind = NULL;
- char sPath[2048];
-
- // 构建文件路径模式
- sprintf(sPath, "%s\\*.*", sDir);
-
- if ((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE) {
- printf("Path not found: [%s]\n", sDir);
- return;
- }
-
- do {
- // 忽略 "." 和 ".."
- if (strcmp(fdFile.cFileName, ".") != 0 && strcmp(fdFile.cFileName, "..") != 0) {
- sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);
-
- // 如果是目录, 递归调用自身
- if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
- DeleteDirectoryContents(sPath);
- if (RemoveDirectory(sPath)) { // 尝试删除目录
- printf("Directory deleted: %s\n", sPath);
- } else {
- printf("Failed to delete directory: %s\n", sPath);
- }
- }
- else {
- if (DeleteFile(sPath)) { // 尝试删除文件
- printf("File deleted: %s\n", sPath);
- } else {
- printf("Failed to delete file: %s\n", sPath);
- }
- }
- }
- } while (FindNextFile(hFind, &fdFile)); // 查找下一个文件
-
- FindClose(hFind);
- }
-
- int main() {
- char tempPath[MAX_PATH];
- GetTempPath(MAX_PATH, tempPath); // 获取临时文件夹路径
-
- printf("Deleting contents of: %s\n", tempPath);
- DeleteDirectoryContents(tempPath);
-
- printf("Cleanup completed.\n");
-
- return 0;
- }