Program to Display its own Source Code as Output - (C Programs)
In this tutorial, we will discuss how to write a C program that will display its own source code as output. This program is a simple demonstration of how we can read and print the contents of a file in C.
Syntax
#include <stdio.h>
int main()
{
FILE *fp;
char c;
fp = fopen(__FILE__, "r");
do {
c = getc(fp);
putchar(c);
} while(c != EOF);
fclose(fp);
return 0;
}
Example
#include <stdio.h>
int main()
{
FILE *fp;
char c;
fp = fopen(__FILE__, "r");
do {
c = getc(fp);
putchar(c);
} while(c != EOF);
fclose(fp);
return 0;
}
Output
When you run the program, the output will be the exact same code that you wrote.
Explanation
The program uses the fopen()
function to open its own source file in read-only mode. It then reads the contents of the file character by character using the getc()
function and prints each character to the console using the putchar()
function. The program continues to read and print characters until it reaches the end of the file (EOF
). Finally, the program closes the file and exits.
Use
This program can be used to demonstrate file handling and basic input/output operations in C programming. It can also be used as a simple test program to verify that the C compiler is functioning correctly.
Summary
In this tutorial, we learned how to write a C program that displays its own source code as output. We discussed the syntax, example, explanation, use case, and output of the program. By reading its own source code, this program demonstrates basic file handling and input/output operations in C programming.