Help with ReadFile win api

Can the second parameter of ReadFile be a WCHAR* buffer instead of a CHAR* buffer?
I use GetFileSize to read file size
1
2
3
4
5
6
7
8
//hFile was opened with CreateFile
DWORD size = GetFileSize(hFile, 0);
if(size != 0xFFFFFFFF)
{
DWORD read;
WCHAR* pszText= (WCHAR*)GlobalAlloc(GPTR, size+1);
ReadFile(hFile, pszText, size, &read, 0);
...

Since size is the number of bytes, and a WCHAR is 2 bytes, would i need to declare pszText as GlobalAlloc(GPTR, (size/2)+1) if the buffer is WCHAR?
Last edited on
ReadFile writes the content of a contiguous buffer. So you need to specify the start of the buffer and its length.

You can pass WCHAR* in, but you need to remember that WCHAR is two bytes, so you must use that to multiply the string length when passed to ReadFile/WriteFile, send/recv, sendto/recvfrom, ...
I need to set the contents of an edit box with the text I read from the file.
GetFileSize returns the number of bytes in a file. Wouldn't you be reading past the contents of the file if you multiply the number of the bytes to read by 2 like this?
 
ReadFile(hFile, pszText, size*2, &read, 0);

What if I just used this instead of WCHARS, would it work with unicode too?
 
LPBYTE pszText = (LPBYTE)GlobalAlloc(GPTR, size+1);

The edit box was created with CreateWindowExW and I'm using SendMessage instead of SetWindowText since SetWindowText accepts only a buffer of signed CHARS
Last edited on
You could use the binary block read/write stuff, but as you're just dealing with strings, why not just do string/file stuff?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <fstream>
#include <iostream>

int main()
{
	{
		std::wstring msg = L"Hello world\n";

		std::wofstream os(L"C:\\temp\\stuff.txt");
		os << msg;
	}
	{
		std::wifstream os(L"C:\\temp\\stuff.txt");

		std::wstring line;
		while (std::getline(os, line))
			std::wcout << line << L"\n";
	}
}
Last edited on
Topic archived. No new replies allowed.