【发布时间】:2020-06-24 02:54:06
【问题描述】:
我创建了一个将原始数据写入 USB 驱动器的函数:write(int size,wchar_t data[])。 data是要写入的数据,size是数据的长度。
bool write(int size, wchar_t data[])
{
HANDLE hDevice = INVALID_HANDLE_VALUE; // handle to the drive to be written
hDevice = CreateFile(
GetUSBdrivePath('e'), // GetUsbdrivePath(char) returns the file path
(GENERIC_READ | GENERIC_WRITE), // access mode to the drive
FILE_SHARE_WRITE, //Shared or exclusive
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL);
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
cout << GetLastError();
return (FALSE);
}
wchar_t *keybuffer = data;
//Sets the start position of the pointer from where it has to write
if (SetFilePointer(
hDevice,
((2)*512),
NULL,
FILE_BEGIN)
== INVALID_SET_FILE_POINTER)
{
CloseHandle(hDevice);
return false;
}
DWORD NumberOfBytesRead = 0;
DWORD dwSize = static_cast<DWORD>(size);
bool flag = WriteFile(hDevice, keybuffer, dwSize, &NumberOfBytesRead, (LPOVERLAPPED)NULL);
CloseHandle(hDevice);
return flag;
}
当写入的数据大小为512或其倍数时,该功能正常工作。但是当大小不是 512 的倍数时,WriteFile() 无法写入。我已阅读 Microsoft 的文档,但找不到任何有用的东西。为什么会这样?
【问题讨论】: