C Program to Display its own Source Code as Output

In this example, you’ll learn to display source of the program using __FILE__ macro.

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 using __FILE__

  1. #include <stdio.h>
  2. int main() {
  3. FILE *fp;
  4. int c;
  5. fp = fopen(__FILE__,"r");
  6. do {
  7. c = getc(fp);
  8. putchar(c);
  9. }
  10. while(c != EOF);
  11. fclose(fp);
  12. return 0;
  13. }

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.