You can use MultibyteToWideChar()
function to perform the actual conversion (MSDN page). There is no need to add slashes - they are just escape sequences which represent a single '\'
in your program code.
Parse string to LPCWSTR
-
18-09-2022 - |
Question
I am working with boost-filesystem to search all the files in a concrete path. I also want to retrieve this file's creation data, last opening and last update so as I am working in Windows I need to use the GetFileTime (which requires a HANDLE that I will get by the CreateFile function.
The point is that by boost filesystem I get a string such as
string filename="C:\Users\MyUser\Desktop\PDN.pdf";
and I need to convert this string to a LPCWSTR.
Because of this I have done several tries which have all failed, for example:
HANDLE hFile = CreateFile((LPCWSTR)fileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
But when doing this, it succeded:
HANDLE hFile = CreateFile(L"C:\\Users\\MyUSer\\Desktop\\PDN.pdf", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
So my question is, how could I parse a string to a PWSTR using a string variable? And if possible (I guess no), is there any function that will change the original path adding a slash where finds another slash?
Thanks a lot
EDITED: This is the way I have done it after what I have read in here:
wstring fileFullPathWstring = winAPII.stringToWstring(iter->path().string());
HANDLE hFile = CreateFile(fileFullPathWstring.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
Using the function:
wstring WinAPIIteraction::stringToWstring(string stringName){
int len;
int slength = (int)stringName.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, stringName.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, stringName.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
Solution
OTHER TIPS
Simplest solution:
wstring filename="C:\Users\MyUser\Desktop\PDN.pdf";
HANDLE hFile = CreateFile(
fileName.c_str(), // std::wstring::c_str returns wchar_t*
GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
Use CA2W from ATL for that:
string filename="C:\Users\MyUser\Desktop\PDN.pdf";
HANDLE hFile = CreateFile(CA2W(fileName.c_str()), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
I know that it´s late but this is a method I am using to convert a string into LPCWSTR:
typedef long long long64;
/**Don´t forget to use delete*/
LPCWSTR convStringToLPCWSTR(string String)
{
char *cString = &String[0u];
long64 size = strlen(cString);
wchar_t* wString = new wchar_t[size];
for (long64 i = 0; i < size; i++)
{
wString[i] = cString[i];
}
wString[size] = 0; //important, otherwise Windows will print whatever next in memmory until it finds a zero.
return wString;
}