C Program to Display its own Source Code as Output of Program
C Program to Display its own Source Code as Output of Program.
In this article, you will learn how to write a c program that produces its own source code as its output of the program.
- In this given program
__FILE__
macros will return the current file name of the program. - Then
fopen
function will open this input file. - After that with the help of
getc
&putchar
functions, It will read the characters. - Then It will display these characters immediately.
- In the last given program, It will print the itself code.
You should know about the following topics in C programming to understand this program:
- C Pointers
- C __FILE__ Macros
- C fopen Function
- C getc Function
- C putchar Function
Source
// C program to Display its own Source Code as Output
#include <stdio.h>
// It's the main function of the program
int main() {
FILE *file_pointer;
int program_character;
// Step-1 Open the current file as an input
file_pointer = fopen(__FILE__,"r");
// Step-2 Read character's from the input file & Then display these characters on time
do {
program_character = getc(file_pointer);
putchar(program_character);
}
while (program_character != EOF); // Loop will stop until the end of the file is reached
// Step-3 Close the input file
fclose(file_pointer);
printf("\n");
return 0;
}
Output
// C program to Display its own Source Code as Output
#include <stdio.h>
// It's the main function of the program
int main() {
FILE *file_pointer;
int program_character;
// Step-1 Open the current file as an input
file_pointer = fopen(__FILE__,"r");
// Step-2 Read character's from the input file & Then display these characters on time
do {
program_character = getc(file_pointer);
putchar(program_character);
}
while (program_character != EOF); // Loop will stop until the end of the file is reached
// Step-3 Close the input file
fclose(file_pointer);
printf("\n");
return 0;
}