Thursday, August 8, 2024

Print their own source code as output in C.

Print their own source code as output in C. 


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.


Example
code:

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



output
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;
}

No comments:

Post a Comment