Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format drive by c++

Tags:

c++

winapi

I want to format a drive in c++, but when I tried to use Format function of windows.h I could not find a sample or the way of using that. I also don't want to interact by user in order to get ok or cancel so I cannot use SHFormat

Does anyone know how can I do that?

like image 255
JGC Avatar asked Apr 15 '10 19:04

JGC


2 Answers

You might use the SHFormatDrive function to display the Format Drive dialog box in Windows.

like image 58
Andreas Rejbrand Avatar answered Oct 07 '22 16:10

Andreas Rejbrand


You can use CreateProcess to launch a hidden copy of the cmd.exe format command, and feed it characters to handle the prompting. This is in Pascal, but it's all API calls, so it should translate pretty easily. You'll need to add some error handling too, and make sure you test it extensively.

Win32_Volume::Format was only added in Windows 2003, so it won't work if you need WinXP or Win2K support.

procedure FormatFloppy;
var
  sa: TSecurityAttributes;
  si: TStartupInfo;
  pi: TProcessInformation;
  BytesWritten: LongWord;
  hInRead, hInWrite: THandle;
begin
  // Initialize security information
  sa.nLength := SizeOf(sa);
  sa.lpSecurityDescriptor := nil;
  sa.bInheritHandle := True;
  CreatePipe(hInRead, hInWrite, @sa, 0);
  // Initialize startup info
  ZeroMemory(@si, SizeOf(si));
  si.cb := SizeOf(si);
  si.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
  si.wShowWindow := SW_HIDE;
  si.hStdInput := hInRead;
  si.hStdOutput := GetStdHandle(STD_OUTPUT_HANDLE);
  si.hStdError := GetStdHandle(STD_ERROR_HANDLE);
  // Start process
  ZeroMemory(@pi, SizeOf(pi));
  CreateProcess(nil, 'cmd /c format a: /fs:FAT /F:1.44 /V:', nil, nil, True,
    CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, si, pi);
  CloseHandle(pi.hThread);
  CloseHandle(hInRead);
  // Write '<enter>' to start processing, and 'n<enter>' to respond to question at end
  WriteFile(hInWrite, #13#10'N'#13#10, 5, BytesWritten, nil);
  CloseHandle(hInWrite);
  // Wait for process to exit
  WaitForSingleObject(pi.hProcess, INFINITE);
  CloseHandle(pi.hProcess);
end;
like image 29
Zoë Peterson Avatar answered Oct 07 '22 16:10

Zoë Peterson