Cannot convert wchar_t

Hey I had a code problem it, this is the error:

1
2
error C2664: 'CreateFileA' : cannot convert parameter 1 from 'const wchar_t *' to 'LPCSTR'
          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast


and the function:

1
2
3
4
LoadingStream::LoadingStream(const wchar_t *fileName)
{
	hFile = CreateFile(fileName, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
}


I've googled around but couldn't find suitable discussions around this.
Thanks in advance.
wchar_t is a unicode datatype, which is different then the ASCII function you are specifying.

Just define LoadingStream with a const char*, or use CreateFileW(...)
1
2
3
4
5
LoadingStream::LoadingStream(const wchar_t *fileName){
   wstring myWstring(fileName);
   string strFileName= std::string(myWstring.begin(),myWstring.end());
   hFile = CreateFile(strFileName.c_str(), GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
}
Last edited on
...except that that throws away any Unicode information that might be in the filename, producing upset users.

Why not just use CreateFileW() as pogrady suggests?
Thanks! Worked flawless with CreateFileW, also with const char* instead of const wchar_t* it made me run into problems when I would need to change char in all other functions and it ended up with, that it said it cannot convert wchar once again even if it wasn't there? Anyways worked fine with CreateFileW. clanmjcs code had undefined strings?
Last edited on
undefined strings?
What do you mean?
He probably did not #include <string>.
I need to create copypasta out of this or something...

WinAPI functions/structs which use strings come in 3 varieties:

- TCHAR versions (TCHAR, LPCTSTR, LPTSTR)
- char versions (char, LPCSTR, LPSTR)
- wchar_t versions (WCHAR, LPCWSTR, LPWSTR)

Unless you want to convert between different char types in your program, I suggest you just use the function/struct that takes whatever form of string you're using.

The "normal" name for functions/structs take TCHARs. Add an 'A' to the end for the char version, and add a 'W' to the end for the wchar_t version:

1
2
3
CreateFile <-  takes TCHARs
CreateFileA <- takes chars
CreateFileW <- takes wchar_ts


It's just that simple.
Topic archived. No new replies allowed.