Program name: Difference between revisions
No edit summary |
(Added C++ example) |
||
Line 5: | Line 5: | ||
C has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C can access the executable's filename. |
C has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C can access the executable's filename. |
||
<lang c>#include <stdio.h> |
|||
⚫ | |||
⚫ | |||
printf("Executable: %s\n", argv[0]); |
printf("Executable: %s\n", argv[0]); |
||
return 0; |
|||
}</lang> |
|||
=={{header|C++}}== |
|||
C++ has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C++ can access the executable's filename. |
|||
<lang cpp>#include <iostream> |
|||
using namespace std; |
|||
int main(int argc, char **argv) { |
|||
cout << "Executable: " << argv[0] << endl; |
|||
return 0; |
return 0; |
Revision as of 23:56, 5 August 2011
It is useful to programmatically access a program's name, e.g. for determining whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".
C
C has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C can access the executable's filename.
<lang c>#include <stdio.h>
int main(int argc, char **argv) { printf("Executable: %s\n", argv[0]);
return 0; }</lang>
C++
C++ has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C++ can access the executable's filename.
<lang cpp>#include <iostream>
using namespace std;
int main(int argc, char **argv) { cout << "Executable: " << argv[0] << endl;
return 0; }</lang>