void deleteFile()

in src/main/cpp/cleaner/windows/src/main.c [259:301]


void deleteFile(WCHAR * filePath) {
    BOOL canDelete = TRUE;
    DWORD count = 0 ;
    WIN32_FILE_ATTRIBUTE_DATA attrs;
    DWORD filePathLength = lstrlenW(filePath);
    DWORD prefixLength = (filePath == search(filePath, UNC_STD_PREFIX)) ? 0 : UNC_PREFIX_LENGTH;
    DWORD length = filePathLength + prefixLength + 1;
    WCHAR * file = (WCHAR*) LocalAlloc(LPTR, sizeof(WCHAR) * length);
    DWORD i=0;
    for(i=0;i<prefixLength;i++) {
        file[i]=UNC_PREFIX[i];
    }
    for(i=0;i<filePathLength;i++) {
        file[i+prefixLength] = filePath[i];
    }

    // Implementation note:
    // GetFileAttributesExW() is used not only to get file attributes
    // but also as a way to check if the file/dir (still) exist.

    if(GetFileAttributesExW(file, GetFileExInfoStandard, &attrs)) {
      if (attrs.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { // if read-only attrib is set
            if (SetFileAttributesW(file, FILE_ATTRIBUTE_NORMAL) == 0) { // remove read-only attrib
                // The read-only attrib could not be deleted. No point in continuing.
                canDelete = FALSE;
            }
        }
        if (canDelete) {
            if (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                while ((!RemoveDirectoryW(file) || GetFileAttributesExW(file, GetFileExInfoStandard, &attrs)) &&
                        ((count++) < MAX_ATTEMPTS)) {
                    Sleep(SLEEP_DELAY);
                }
            } else {
                while ((!DeleteFileW(file) || GetFileAttributesExW(file, GetFileExInfoStandard, &attrs)) &&
                        ((count++) < MAX_ATTEMPTS)) {
                    Sleep(SLEEP_DELAY);
                }
            }
        }
    }
    LocalFree(file);
}