Program name: Difference between revisions
Content added Content deleted
(→{{header|AWK}}: {{incorrect}}) |
(→{{header|C}}: Add Windows with GetModuleFileNameW. (Resembles the other languages that already call GetModuleFileName.)) |
||
Line 105: | Line 105: | ||
__progname: fakename |
__progname: fakename |
||
p_comm: myname</pre> |
p_comm: myname</pre> |
||
=== Windows === |
|||
[http://msdn.microsoft.com/en-us/library/ms683197%28v=VS.85%29.aspx GetModuleFileName], from the Win32 API, provides the correct path to the current executable file. |
|||
{{libheader|Win32}} |
|||
<lang c>#include <windows.h> |
|||
#include <stdlib.h> |
|||
#include <wchar.h> |
|||
/* |
|||
* Returns the path to the current executable file, in a newly |
|||
* allocated buffer. Use free() to free it. |
|||
*/ |
|||
wchar_t * |
|||
exepath(void) |
|||
{ |
|||
wchar_t *buf, *newbuf; |
|||
long blen, flen; |
|||
/* |
|||
* Most paths fit in MAX_PATH == 260 characters, but very |
|||
* long UNC paths might require a larger buffer. |
|||
*/ |
|||
buf = NULL; |
|||
for (blen = MAX_PATH; 1; blen += MAX_PATH) { |
|||
/* Enlarge buffer. */ |
|||
newbuf = realloc(buf, blen * sizeof buf[0]); |
|||
if (newbuf == NULL) { |
|||
free(buf); |
|||
return NULL; |
|||
} |
|||
buf = newbuf; |
|||
flen = GetModuleFileNameW(NULL, buf, blen); |
|||
if (flen == 0) { |
|||
free(buf); |
|||
return NULL; |
|||
} |
|||
if (flen < blen) |
|||
return buf; |
|||
} |
|||
} |
|||
/* |
|||
* Print the path to this executable. |
|||
*/ |
|||
int |
|||
main() |
|||
{ |
|||
wchar_t *path; |
|||
path = exepath(); |
|||
if (path == NULL) { |
|||
wprintf(L"Sorry, an error occured.\n"); |
|||
return 1; |
|||
} |
|||
wprintf(L"Path to executable: %ls\n", path); |
|||
free(path); |
|||
return 0; |
|||
}</lang> |
|||
<pre>Path to executable: C:\Users\kernigh\Documents\field\scratch.exe</pre> |
|||
=={{header|C++}}== |
=={{header|C++}}== |