Wednesday 20 August 2014

Filled Under:

C Program to Display its own Source Code as Output

Share

Here is source code of the C Program to display its own source code as its output.The C program is successfully compiled and run on a Linux system.The output of this program is given below.
Though this problem seems complex but, the concept behind this program is very simple; display the content from the same file you are writing the source code.
Procedure to display its own source code in C programming

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 as output

#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 on linux system
Output:
$ cc pgm39.c
$ a.out
 
/*
 * C Program to display its own source code as its output
 */
#include <stdio.h>
 
int main()
{
    FILE *fp;
    char ch;
 
    fp = fopen(__FILE__,"r");
    do
    {
        ch = getc(fp);
        putchar(ch);
     }
     while (ch != 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