C Program to Display its own Source Code as its 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.

advertisement
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>
  5.  
  6. int main()
  7. {
  8.     FILE *fp;
  9.     char ch;
  10.  
  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.

advertisement
Runtime Test Cases
Output:
 
/*
 * 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;
}

Sanfoundry Global Education & Learning Series – 1000 C Programs.

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

advertisement
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.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn