通过c ++格式化驱动器 [英] Format drive by c++

查看:82
本文介绍了通过c ++格式化驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c ++中格式化驱动器,但是当我尝试使用windows.h的格式化函数时,我找不到样本或使用它的方式。
我也不想让用户交互以确定或取消,所以我不能使用SHFormat

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?

推荐答案

您可以使用 CreateProcess 以启动cmd.exe格式命令的隐藏副本,并提供它的字符以处理提示。这是在Pascal,但它是所有API调用,所以它应该很容易翻译。

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仅在Windows 2003中添加,因此不会如果您需要WinXP或Win2K支持,则可以工作。

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;

这篇关于通过c ++格式化驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆