gpt4 book ai didi

c - 删除C中的目录

转载 作者:行者123 更新时间:2023-11-30 18:11:06 25 4
gpt4 key购买 nike

我想删除 C、Windows 中的一个目录。我知道我必须首先删除目录中的所有文件,这是我感到困惑的部分。我找到了SHFileOperationIFileOperation虽然我不明白它们是如何从文档中实现的。

我当前的实现:

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)

最佳答案

解决方案来源:Link

正如解决方案所述,使用此函数时请小心,并确保双空终止 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;
}
}

关于c - 删除C中的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52135961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com