2

-getcwd does not return it at least when debugging with VS 2010.

-i have no access to main's arguments because of the user interface kit i'm using

so is there anything to do?

PS. please note the restrictions before tagging this as duplicate

1

2 Answers 2

6

Use GetModuleFileName() and pass NULL as the first argument:

DWORD last_error;
DWORD result;
DWORD path_size = 1024;
char* path      = malloc(1024);

for (;;)
{
    memset(path, 0, path_size);
    result     = GetModuleFileName(0, path, path_size - 1);
    last_error = GetLastError();

    if (0 == result)
    {
        free(path);
        path = 0;
        break;
    }
    else if (result == path_size - 1)
    {
        free(path);
        /* May need to also check for ERROR_SUCCESS here if XP/2K */
        if (ERROR_INSUFFICIENT_BUFFER != last_error)
        {
            path = 0;
            break;
        }
        path_size = path_size * 2;
        path = malloc(path_size);
    }
    else
    {
        break;
    }
}

if (!path)
{
    fprintf(stderr, "Failure: %d\n", last_error);
}
else
{
    printf("path=%s\n", path);
}
Sign up to request clarification or add additional context in comments.

8 Comments

thanks! for some reason i thought that was C++ only. i'll try it!
it works! i get it in funny form though: it's ..\..\ from the current work directory. which is ok I guess. thanks again!
That sounds odd. It should be the full path of the executable, like C:\Program Files\myapplication\my.exe.
The final parameter to GetModuleFileName() is the number of elements in the array, not the size in bytes. So while it works here I wouldn't routinely use sizeof(exe_path) by itself.
The string returned will use the same format that was specified when the module was loaded. Therefore, the path can be a long or short file name, and can use the prefix "\\?\". For more information, see Naming a File.
|
3

Pass NULL as the first argument of GetModuleFileName.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.