问题
I have an issue with GetCurrentDirectory()
, and i don't really understand why. The thing i don't understand is that it works for XP but not for Seven (or at least on my computer). There is my code:
char dir_name[1024]; // as a global variable
int get_files() {
// ...
DWORD dwRet;
dwRet = GetCurrentDirectory(MAX_PATH, dir_name);
printf("%s\n",dir_name);
printf("%d\n",dwRet);
//...
}
This code will return:
printf("%s\n",dir_name);
-> return "c"
printf("%d\n",dwRet);
-> 42
(which is the right length of the string that should be returned)
I don't understand why dir_name only takes the value "c".
回答1:
I think, the result is Unicode in Windows Seven! and after each ascii character of this function there is zero. And you are printing it by printf
. You should use wide-char functions in your program. Like wprintf
.
Try below code: (Tested in Visual Studio 2008 + Windows 7)
#include <stdio.h>
#include <windows.h>
#include <wchar.h>
WCHAR dir_name[1024]; // as a global variable
int get_files()
{
// ...
DWORD dwRet;
dwRet = GetCurrentDirectory(MAX_PATH, dir_name);
wprintf(L"%s\n", dir_name);
printf("%d\n", dwRet);
//...
return 0;
}
回答2:
Im not sure, but could it be GetCurrentDirectory()
returns 2-byte chars under win7?
In such case you'll be getting a 0 in each second bytes of the char array returned.
So you should use a wide-char aware version of the printf()
function such as wprintf()
.
Also I wonder whether the compiler wouldn't have warned you about something being wrong regarding types.
回答3:
what compiler are you using? Under Visual C++ 2005, GetCurrentDirectory is a macro that resolves to GetCurrentDirectoryW if UNICODE macro is defined and to GetCurrentDirectoryA otherwise. Do you have UNICODE defined by any chance?
来源:https://stackoverflow.com/questions/8026996/getcurrentdirectory-buffer-doesnt-return-the-right-value