C Program to Display its own Source Code as Output


This is a C Program to display its own source code as its output.

Problem Description

This program displays its own source code as its output.

Problem Solution

1. Display the content from the same file you are writing the source code.

Program/Source Code

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 program output is also shown below.

  1. /*
  2.  * C Program to Display its own Source Code as its Output
  3.  */
  4. #include <stdio.h>
  6. int main()
  7. {
  8.     FILE *fp;
  9.     char ch;
  11.     fp = fopen(__FILE__,"r");
  12.     do
  13.     {
  14.         ch = getc(fp);
  15.         putchar(ch);
  16.      }
  17.      while (ch != EOF);
  18.      fclose(fp);
  19.      return 0;
  20. }
Program Explanation

1. Open the file you are currently writing using statement fopen(__FILE__,”r”) and assign it to the pointer fp.
2. Scan the every character of the file and store it in the variable ch. Print it using statement putchar(ch).
3. Do step 2 until EOF (end of file).
4. Then close the file and exit.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases
 * C Program to display its own source code as its output
#include <stdio.h>
int main()
    FILE *fp;
    char ch;
    fp = fopen(__FILE__,"r");
        ch = getc(fp);
     while (ch != EOF);
     return 0;

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

Check this: BCA MCQs | C Books
If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics, go to C Programming Examples.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.