c - 在 C 中删除目录
问题描述
我想删除 C、Windows 中的目录。我知道我必须首先删除目录中的所有文件,这是我感到困惑的部分。我发现SHFileOperation
并且IFileOperation
虽然我不明白它们是如何从文档中实现的。
我目前的实现:
int dir_exists = 0;
snprintf(dir_name, STR_SIZE, "%s\\%s", LOCAL_DIR, tokens[1]);
// Check if directory exists
DWORD dwAttrib = GetFileAttributes(dir_name);
if (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {
dir_exists = 1;
}
if (dir_exists == 1) {
// Remove contents of directory (CURRENTLY UNIX)
DIR *dir;
struct dirent *d;
char filepath[FNAME_SIZE];
dir = opendir(dir_name);
while (d = readdir(dir)) {
sprintf(filepath, "%s/%s", dir_name, d->d_name);
remove(filepath);
}
// Remove directory
if ((RemoveDirectory(dir_name)) == 0) {
printf("Error removing dictionary\n");
return 0;
}
}
我想要一个 Windows 替换没有使用的注释部分,因为#include <dirent.h>
我的 VS 没有这个头文件:
// Remove contents of directory (CURRENTLY UNIX)
解决方案
解决方案信用:链接
正如解决方案所说,使用此功能时请小心,并确保您使用 double null terminate pFrom
。
dir_name[STR_SIZE];
int dir_exists = 0;
snprintf(dir_name, STR_SIZE, "folder/dir_to_be_deleted");
// Check if directory exists
DWORD dwAttrib = GetFileAttributes(dir_name);
if (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {
dir_exists = 1;
}
if (dir_exists == 1) {
// Remove contents of directory
snprintf(dir_name, STR_SIZE, "%s/%s", LOCAL_DIR, tokens[1]);
TCHAR szDir[MAX_PATH];
StringCchCopy(szDir, MAX_PATH, dir_name);
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
int len = _tcslen(szDir);
TCHAR* pszFrom = malloc((len + 4) * sizeof(TCHAR)); //4 to handle wide char
StringCchCopyN(pszFrom, len + 2, szDir, len + 2);
pszFrom[len] = 0;
pszFrom[len + 1] = 0;
SHFILEOPSTRUCT fileop;
fileop.hwnd = NULL; // no status display
fileop.wFunc = FO_DELETE; // delete operation
fileop.pFrom = pszFrom; // source file name as double null terminated string
fileop.pTo = NULL; // no destination needed
fileop.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; // do not prompt the user
fileop.fAnyOperationsAborted = FALSE;
fileop.lpszProgressTitle = NULL;
fileop.hNameMappings = NULL;
if (SHFileOperation(&fileop) != 0) {
printf("Error SHFileOperation\n");
return 0;
}
free(pszFrom);
// Remove directory
if ((RemoveDirectory(dir_name)) == 0) {
printf("Error removing dictionary\n");
return 0;
}
}
推荐阅读
- r - 在 HPC 上加载 pdf 输出 ggsave 时出现问题:有更好的包或更好的格式吗?
- html - 如何向右移动到页面底部
- java - enctype="multipart/form-data" 破坏了我的应用程序
- android-studio - 即时运行快捷方式在 Android Studio 3.3 中不起作用
- angular - Angular PrimeNG p-tree - 如何通过其 id 以编程方式聚焦节点?
- c# - 用于 C# 类层次结构的 MongoDb 顺序 int id 生成器
- python - 在一个 plot() 中绘制多条线时,Pyplot 返回不同的对象
- regex - 使用记事本++上的正则表达式提取以不同值重复的标签
- javascript - 追加限制为 1 时更新变量的值
- php - PHP - 对不同的数组求和