我需要帮助使用DeleteDirectory和DeleteFile API函数删除目录

时间:2012-04-01 11:52:22

标签: c winapi

我编辑我的代码,但我仍然遇到同样的问题,文件不会删除,目录仍未删除,我需要帮助

#include<stdio.h>
#include<Windows.h>
#include<tchar.h>

 void Delete(WIN32_FIND_DATA x);

int main(int argc , char*argv[])
{
    WIN32_FIND_DATA x , d;
    HANDLE f = FindFirstFile(L"d:\\Text\\*.*" , &x);
    if(f == INVALID_HANDLE_VALUE)
    {
        printf("Serach faild\n");
        return 0;
    }

    Delete(x);

    while(FindNextFile(f , &x))
        Delete(x);

    FindClose(f);

    printf("Now I'm going to delete the Directory\n");
    if(RemoveDirectory(L"d:\\Text"))
        printf("Successed\n");
    else
        printf("Did not\n");
}

 void Delete(WIN32_FIND_DATA x)
 {
    if((x.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
         {
            _tprintf(L"The first File name is %s\n" , x.cFileName);
            printf("I'm going To delete The File\n");
            if(DeleteFile(L"d:\\Text\\x.cFileName"))
                printf("File Deleted\n");
            else printf("False\n");
         }

    else
            _tprintf(L"The Directory name is %s\n" , x.cFileName);

 }

我在这段代码中找不到问题,我写了我知道的所有内容,任何人都可以编辑它来工作,并感谢大家

3 个答案:

答案 0 :(得分:0)

删除目录中的所有内容后,它仍将包含“。”条目。和“..”目录,不能删除(除了删除包含目录)。因此,删除目录的代码将永远不会执行,但即使在您成功删除所有内容后,您的第二个FindFirstFile也将始终显示两个条目。

答案 1 :(得分:0)

代码不起作用的原因是Delete函数总是尝试删除名为d:\\Text\\x.cFileName

的文件

相反,你需要这样的东西:

        TCHAR buff[MAX_PATH];
        _tprintf(L"The first File name is %s\n" , x.cFileName);
        printf("I'm going To delete The File\n");
        _stprintf(buff, L"d:\\Text\\%s", x.cFileName);
        if(DeleteFile(buff))
            printf("File Deleted\n");

答案 2 :(得分:0)

您可以使用SHFileOperation功能删除目录及其所有内容。

WCHAR FilePath[MAX_PATH+1]=L"D:\\Text";
SHFILEOPSTRUCT Operation={0};
Operation.wFunc=FO_DELETE;
//FilePath needs to be double-null terminated
FilePath[wcslen(FilePath)+1]=L'\0';
Operation.pFrom=FilePath;
//Don't show any user interface during the operation
Operation.fFlags=FOF_SILENT|FOF_NOCONFIRMATION|FOF_NOERRORUI;
if(SHFileOperation(&Operation)==0) {
    printf("The directory has been deleted.");
}
else {
    //Handle error here
}