Winapi WriteFile function write one byte

I trying binary file write one byte, and get fails... How to get to work?

My code:

unsigned char b = 0x00; // equal to hex value = 00
/*
 Error: GetLastError()
 ERROR_INVALID_USER_BUFFER
 1784 (0x6F8)
 The supplied user buffer is not valid for the requested operation.
*/
WriteFile(file, ( char *)b, 1, &bytesWritten, NULL);

Upvotes: 0

Views: 1649

Answers (1)

w1ck3dg0ph3r
w1ck3dg0ph3r

Reputation: 1011

WriteFile definition is

BOOL WINAPI WriteFile(
  _In_        HANDLE       hFile,
  _In_        LPCVOID      lpBuffer,
  _In_        DWORD        nNumberOfBytesToWrite,
  _Out_opt_   LPDWORD      lpNumberOfBytesWritten,
  _Inout_opt_ LPOVERLAPPED lpOverlapped
);

where lpBuffer is a pointer to the buffer containing the data to be written.

To get a pointer to b you need an address of operator & instead of C-style cast to char pointer:

WriteFile(file, &b, 1, &bytesWritten, NULL);

Upvotes: 3

Related Questions