Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a Unicode path to a c string?

Tags:

c

winapi

How can i convert from a Unicode path name (LPWSTR) to the ASCII equivalent? The library that gets called understands only c strings.

Edit: Okay, I took the GetShortPathName and the WideCharToMultiByte suggestions and created that piece of code, i tested it with some folders containing Unicode characters in the path and it worked flawlessly:

wlength = GetShortPathNameW(cpy,0,0);
LPWSTR shortp = (LPWSTR)calloc(wlength,sizeof(WCHAR));
GetShortPathNameW(cpy,shortp,wlength);
clength = WideCharToMultiByte(CP_OEMCP, WC_NO_BEST_FIT_CHARS, shortp, wlength, 0, 0, 0, 0);
LPSTR cpath = (LPSTR)calloc(clength,sizeof(CHAR));
WideCharToMultiByte(CP_OEMCP, WC_NO_BEST_FIT_CHARS, shortp, wlength, cpath, clength, 0, 0);
like image 559
metafex Avatar asked Jun 01 '10 17:06

metafex


1 Answers

GetShortPathName() Function

http://msdn.microsoft.com/en-us/library/aa364989%28VS.85%29.aspx

Will give you an equivalent 8.3 filename, pointing to the same file, for use with legacy code.

[EDIT] This is probably the best you can do, although theoretically the 8.3 filenames may contain non-ascii characters, depending on registry setting. In this case, you don't have an easy way of getting the proper char*, and GetShortPathNameA() will not do that either if codepage setting during file creation does not match current setting.

See http://technet.microsoft.com/en-us/library/cc781607%28WS.10%29.aspx about the setting. There's a concensus here (see below) that this case is reasonable to neglect.

Thanks Moron, All, for contribution to this post.

like image 132
Pavel Radzivilovsky Avatar answered Sep 22 '22 02:09

Pavel Radzivilovsky