What is the Win32 API function to use to delete a folder?

See uvgroovy's comment above. You need 2 nulls at the end of the 'dir' field.

int silently_remove_directory(LPCTSTR dir) // Fully qualified name of the directory being   deleted,   without trailing backslash
{
  int len = strlen(dir) + 2; // required to set 2 nulls at end of argument to SHFileOperation.
  char* tempdir = (char*) malloc(len);
  memset(tempdir,0,len);
  strcpy(tempdir,dir);

  SHFILEOPSTRUCT file_op = {
    NULL,
    FO_DELETE,
    tempdir,
    NULL,
    FOF_NOCONFIRMATION |
    FOF_NOERRORUI |
    FOF_SILENT,
    false,
    0,
    "" };
  int ret = SHFileOperation(&file_op);
  free(tempdir);
  return ret; // returns 0 on success, non zero on failure.
}

There are two ways to approach this. One is through the File Services (using commands such as DeleteFile and RemoveDirectory) and the other is through the Windows Shell (using SHFileOperation). The latter is recommended if you want to delete non-empty directories or if you want explorer style feedback (progress dialogs with flying files, for example). The quickest way of doing this is to create a SHFILEOPSTRUCT, initialise it and call SHFileOperation, thus:

void silently_remove_directory(LPCTSTR dir) // Fully qualified name of the directory being deleted, without trailing backslash
{
    SHFILEOPSTRUCT file_op = {
        NULL,
        FO_DELETE,
        dir,
        "",
        FOF_NOCONFIRMATION |
        FOF_NOERRORUI |
        FOF_SILENT,
        false,
        0,
        "" };
    SHFileOperation(&file_op);
}

This silently deletes the entire directory. You can add feedback and prompts by varying the SHFILEOPSTRUCT initialisation - do read up on it.


I think you want DeleteFile and RemoveDirectory

Tags:

Winapi