C Program to Display its own Source Code as Output
In this example, you’ll learn to display the program’s source using the __FILE__ macro.
Though this problem seems complex but, the concept behind this program is straightforward; display the content from the exact file you are writing the source code.
A predefined macro __FILE__ contains the location of a C programming file, it is working on. For example:
#include <stdio.h>
int main()
{ printf("%s",__FILE__); }
The output of this program is the location of this C programming file.
C program to display its own source code using __FILE__
#include <stdio.h>
int main() {
FILE *fp;
int c;
fp = fopen(__FILE__,"r");
do {
c = getc(fp);
putchar(c);
}
while(c != EOF);
fclose(fp);
return 0;
}
This program displays the content of this particular C programming file(source code) because __FILE__ contains the location of this C programming file in a string.
C program that displays its own source code as output:
#include <stdio.h>
int main() {
FILE *fp;
char c;
fp = fopen(__FILE__, "r");
if (fp) {
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
}
return 0;
}
Explanation:
#include <stdio.h>
includes the standard input-output header file in our program which provides the functionality for input and output operations.int main()
is the entry point of our program.FILE *fp;
declares a file pointer variablefp
which will be used to open and read the source code file.char c;
declares a character variablec
that will be used to store each character read from the source code file.fp = fopen(__FILE__, "r");
opens the source code file in read mode and assigns the file pointer tofp
.__FILE__
is a predefined macro in C which expands to the name of the current source file.if (fp) { ... }
checks if the file was opened successfully. If the file was opened successfully, the code inside the curly braces is executed, otherwise, it is skipped.while ((c = fgetc(fp)) != EOF) { putchar(c); }
reads each character from the source code file usingfgetc()
and prints it to the console usingputchar()
. The loop continues until the end of the file (EOF
) is reached.fclose(fp);
closes the file.
When we compile and run this program, it will read and print its own source code to the console.