×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to print program's name

Here, we are going to learn how can we print the program's name in C language? Here, is a program that will print the name of its executable file name (program name).
By IncludeHelp Last updated : March 10, 2024

If we want to print the name of the program, we have to understand, what is program's name?

Since program name is the name of source file like prog.c. But, here in this program, please consider program name is the name of executable file (like prog – which is created after compilation of the program) that we are going to print using program.

Prerequisite

  1. Execution process of a C/C++ program.
  2. Command line arguments in C programming.

I would recommend reading above mentioned posts. If you already know about these topics, we can proceed.

How to get and print the program's name in C/C++?

Consider the standard Linux GCC/G++ compiler. Let's know about the command to execute program in GCC/G++ compiler.

 ./program_name

Here, program_name is the executable file name and we have to print this file name using C program. The parameter which are being passed through the command line can be scanned in the program through command line arguments.

To scan/get the parameters which are supplied through the command line, we use following syntax of the main function

 int main(int argc, char *argv[])

Here, argc is an integer type of arguments, which contains the total number of arguments/parameters supplied through the command line and argv[] is an array of character pointer (array of strings), which contains the all parameters.

Here is the list of some of the command line argument based programs in C.

In this program, we are learning how to print program's name? – program's name is ./program_name which is the first (0th index) parameter of the parameter list.

Consider the program

C program to print program's name

#include <stdio.h>

int main(int argc, char *argv[]) {
	printf("program's name is: %s\n",argv[0]);
	return 0;
}

Output

program's name is: ./prog

Note

If you are using a compiler, which has different syntax of executing the program like compiler_name program_name, in that case second (1st index) parameter will be the name of the program.

C Command Line Arguments Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.