Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program, that prints its executable file name

Tags:

c++

c

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"?

like image 319
siddstuff Avatar asked Nov 26 '14 12:11

siddstuff


Video Answer


2 Answers

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.

like image 116
galinette Avatar answered Sep 19 '22 13:09

galinette


#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;
}
like image 26
David Ranieri Avatar answered Sep 19 '22 13:09

David Ranieri