• C system()函数调用删除Windows临时目录下的所有文件


    1. #include
    2. #include
    3. int main() {
    4. // 删除Windows临时目录下的所有文件和子目录
    5. system("del /s /q %temp%\\*.*");
    6. system("for /d %x in (%temp%\\*) do @rd /s /q \"%x\"");
    7. printf("Temporary files and directories deleted successfully.\n");
    8. return 0;
    9. }

    代码解释

    • 第一个 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 遍历指定目录下的所有文件和子目录。
    • 使用 FindFirstFileFindNextFile 遍历文件,DeleteFile 删除文件,RemoveDirectory 删除目录。
    • 避免了使用 system() 函数,减少了由于外部命令注入带来的安全风险。
    1. #include
    2. #include
    3. void DeleteDirectoryContents(const char *sDir) {
    4. WIN32_FIND_DATA fdFile;
    5. HANDLE hFind = NULL;
    6. char sPath[2048];
    7. // 构建文件路径模式
    8. sprintf(sPath, "%s\\*.*", sDir);
    9. if ((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE) {
    10. printf("Path not found: [%s]\n", sDir);
    11. return;
    12. }
    13. do {
    14. // 忽略 "." 和 ".."
    15. if (strcmp(fdFile.cFileName, ".") != 0 && strcmp(fdFile.cFileName, "..") != 0) {
    16. sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);
    17. // 如果是目录, 递归调用自身
    18. if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
    19. DeleteDirectoryContents(sPath);
    20. if (RemoveDirectory(sPath)) { // 尝试删除目录
    21. printf("Directory deleted: %s\n", sPath);
    22. } else {
    23. printf("Failed to delete directory: %s\n", sPath);
    24. }
    25. }
    26. else {
    27. if (DeleteFile(sPath)) { // 尝试删除文件
    28. printf("File deleted: %s\n", sPath);
    29. } else {
    30. printf("Failed to delete file: %s\n", sPath);
    31. }
    32. }
    33. }
    34. } while (FindNextFile(hFind, &fdFile)); // 查找下一个文件
    35. FindClose(hFind);
    36. }
    37. int main() {
    38. char tempPath[MAX_PATH];
    39. GetTempPath(MAX_PATH, tempPath); // 获取临时文件夹路径
    40. printf("Deleting contents of: %s\n", tempPath);
    41. DeleteDirectoryContents(tempPath);
    42. printf("Cleanup completed.\n");
    43. return 0;
    44. }

     

  • 相关阅读:
    2023年网络安全行业:机遇与挑战并存
    释放C盘空间:WinSXS文件夹真实性大小判断及释放占用空间
    C++学习 --函数
    M3U8 格式:为什么直播回放都用这个格式?丨音视频基础
    信息学奥赛一本通(c++):1127:图像旋转
    最新android icon和splashScreen适配兼容至2024android
    java毕业生设计重工教师职称管理系统计算机源码+系统+mysql+调试部署+lw
    数据好合: Argilla 和 Hugging Face Spaces 携手赋能社区合力构建更好的数据集
    MySql入门教程--MySQL数据库基础操作
    TrackBar控件
  • 原文地址:https://blog.csdn.net/book_dw5189/article/details/141289800