• 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. }

     

  • 相关阅读:
    docker部署rustdesk远程控制服务器
    VUE右键菜单 vue-contextmenujs的使用
    React框架下如何集成H.265网页流媒体视频播放器EasyPlayer.js?
    《算法系列》之设计
    离线升级:openssh从8.1版本至8.4版本
    Git 的基本概念和使用方式
    cario库
    mybatis的缓存机制
    [开源]基于Vue的拖拽式数据报表设计器,为简化开发提高效率而生
    git本地分支代码合并到主分支,主分支合并到我的分支
  • 原文地址:https://blog.csdn.net/book_dw5189/article/details/141289800