dyesdyes
dyesdyes

Reputation: 1217

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

Upvotes: 2

Views: 2504

Answers (3)

marcinj
marcinj

Reputation: 50016

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?

Upvotes: 1

masoud
masoud

Reputation: 56509

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

Upvotes: 3

alk
alk

Reputation: 70971

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.

Upvotes: 2

Related Questions