Suppose source code file name is test.cpp
. When it is compiled, it produce test.exe
file. When I execute it, it should identify its file name that is test.exe
and print it.
I'm able to get list of all the files and directories present in the current directory using following code:
DIR * directory;
struct dirent * direct;
direct = readdir(directory);
But, how can I identify the associated file name, in this case which is "test.exe"
?
In your main function, argv[0]
is the name of the executable from the command line
#include <stdio.h>
int main(int argc, char ** argv)
{
printf("%s", argv[0]);
return 0;
}
Live Demo
This prints the command name, which is the directory relative to the current working directory, plus the executable name (if available, which is not guaranteed)
To get the current working directory, use getcwd()
standard library C function.
Extracting the file name from the command path in argv[0]
is platform specific : unix use slashes '/
', windows allows mixed uses of slash /
and backslash \
, and any other platform could use any other path separator. Extracting the file name from a path requires a cross-platform library, such as Qt or Boost. On POSIX environments, basename could be used.
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%s\n", argv[0]);
return 0;
}
Note that your program can be launched as:
/home/user/./app
In this case you can get the name by using strrchr
:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *appname;
appname = strrchr(argv[0], '/'); /* '\\' on Windows */
printf("%s\n", appname ? ++appname : argv[0]);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With