GetCurrentDirectory buffer doesn't return the right value

拟墨画扇 提交于 2020-02-22 07:40:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!