getDirectory of FileSystem.d

Frits van Bommel fvbommel at
Wed Feb 14 12:54:06 PST 2007

Alberto wrote:
> int length = GetCurrentDirectoryW (0, null);
> if (length) {
>     char[MAX_PATH] tmp = void;
>     auto dir = new wchar [length];
>     GetCurrentDirectoryW (length, dir.ptr);
>     return new FilePath (Utf.toUtf8 (dir, tmp));
> }
> null is passed as buffer to GetCurrentDirectoryW, so the return value
> should specifies the required size of the buffer including the
> null-terminating character, but D string doesn't have one.
> So, this line:
> auto dir = new wchar [length];
> should be fixed in:
> auto dir = new wchar [length-1];
> and the same for the ANSI version
> or I'm wrong?

The code is wrong, but I think you're also wrong about how to fix it ;).

GetCurrentDirectoryW will _still_ try to write the null character to 
terminate the string. So space for it needs to be allocated. Since the 
null character shouldn't be returned, the length of 'dir' should be 
decreased by one before use.

So the fix is to either insert something like 'dir = dir[0 .. $-1];' (or 
'dir.length = length - 1;') before the return statement, or to change 
the 'dir' in the return statement to 'dir[0 .. $-1]'.

More information about the Digitalmars-d-learn mailing list