Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c++ - C program, that prints its executable file name

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...