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

#include <stdio.h>
#include <stdlib.h>

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 遍历指定目录下的所有文件和子目录。
  • 使用 FindFirstFileFindNextFile 遍历文件,DeleteFile 删除文件,RemoveDirectory 删除目录。
  • 避免了使用 system() 函数,减少了由于外部命令注入带来的安全风险。
#include <windows.h>
#include <stdio.h>

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;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值