Thanks to @Remy for the ShellExecuteEx suggestion, here are the bad details. Pay attention to the use of "cmd" and the double command, so the user only needs to answer once. In addition, [1] must wait for the process to complete, otherwise you could create a file before deleting it, and [2] did not wait for the process if it did not work.
// delete file with Admin privilege // 'file_name' is path of file to be deleted SHELLEXECUTEINFO shex; char param[512]; char *cmd = "/C \"attrib -H \"%s\" && del /F /Q \"%s\"\""; // double command _snprintf(param, sizeof(param), cmd, file_name, file_name); ZeroMemory(&shex, sizeof(shex)); shex.cbSize = sizeof(shex); shex.lpVerb = "runas"; // runas, open shex.lpFile = "cmd"; // not 'del' shex.lpParameters = param; shex.nShow = SW_HIDE; shex.fMask = SEE_MASK_NOCLOSEPROCESS; BOOL retshx = ShellExecuteEx(&shex); // wait otherwise could return before completed if(retshx) { time_t st = clock(); DWORD exitCode; do { if(!GetExitCodeProcess(shex.hProcess, &exitCode)) break; if(clock() - st > CLOCKS_PER_SEC * 5) // max 5 seconds break; } while(exitCode != STATUS_WAIT_0); // STILL_ACTIVE CloseHandle(shex.hProcess); }
source share