简体   繁体   中英

GetCurrentDirectory buffer doesn't return the right value

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".

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;
}

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM