Why does the following snippet only print out `C` and not the entire path which is way longer??
Code:LPTSTR lpBuffer = (LPTSTR)malloc(256*2); GetCurrentDirectory(256, lpBuffer); MessageBoxA(NULL, (LPCSTR)lpBuffer, (LPCSTR)"Path", MB_OK);
Why does the following snippet only print out `C` and not the entire path which is way longer??
Code:LPTSTR lpBuffer = (LPTSTR)malloc(256*2); GetCurrentDirectory(256, lpBuffer); MessageBoxA(NULL, (LPCSTR)lpBuffer, (LPCSTR)"Path", MB_OK);
Note: your post is concerned with Windows programming, not C programming.
Probably because of something else in your program, or in your choice of compiler, or in compiler settings, or in linker settings that you have omitted. There is an almost infinite number of ways those things might affect behaviour of that snippet, and nobody other than you can even guess what they might be.
When asking a question in a forum, the onus is on YOU to provide relevant context, and to post your question in a forum where it is relevant. You have not done that.
Presumably a wide-character problem.
If you're in unicode mode your GetCurrentDirectory will resolve to GetCurrentDirectoryW and return a wide-character string. These strings will (most likely in your situation) have a zero-byte every second byte.
But then you're printing the string with MessageBoxA, which expects a char string. It interprets the first zero-byte as the end of the string.
You need to get these things straight. You're declaring lpBuffer as a LPTSTR (which will resolve to LPWSTR in unicode mode and LPSTR otherwise) but then casting it to LPCSTR (not only a char string, but constant for some reason).
MessageBox (or explicitly MessageBoxW) will display the wide string properly.
EDIT: Read these
MSDN: Conventions for Function Prototypes
MSDN: Using Generic Data Types
Last edited by oogabooga; 01-25-2014 at 01:38 AM.
The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss
Thanks for bringing it to my notice. I need some more research on conventions and data types. char's,TCHAR's, WCHAR's, _TCHAR's and all other jumble of data types are particularly confusing and dissuading. Also, what methods do you suggest for string concatenation?? I use strcat and strcat_s but for whatever reasons they change a fairly intelligible English string into a not so amusing Japanese one.
I would forget about trying to use TCHAR's - they won't be useful to you. Instead, change your compiler settings to either 1) Turn off Unicode and only use char-based types/functions - like strcat() etc. 2) Turn on Unicode and only use wchar_t-based types/functions. Whether or not you explicitly use the trailing A/W is up to you. I tend to use them when posting code so that it just works regardless of the Unicode settings.
gg