【问题标题】:Writefile() fails to write data depending on length of dataWritefile() 根据数据长度写入数据失败
【发布时间】: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 的文档,但找不到任何有用的东西。为什么会这样?

【问题讨论】:

    标签: c++ winapi


    【解决方案1】:

    您必须一次写入整个扇区。这意味着写入驱动器扇区大小的偶数倍的偏移量,并将数据块写入扇区大小的倍数的偏移量。

    如果你的data不是一个完整扇区的偶数倍,你仍然需要写一个完整的扇区。计算所需扇区开始的起始偏移量,将size 值舍入到data 结束位置之后的下一个扇区边界,分配从起始偏移量到结束边界的总大小的内存块,复制data在需要的地方写入该块,然后将整个块写入驱动器。

    如果您想写入比完整扇区更少的字节,并且不想在 data 字节之前/之后覆盖现有数据,那么您必须先将现有扇区读入分配的内存块,然后根据需要将 data 字节复制到该块中,然后将整个块写回驱动器。

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多