Display its Own Source Code as Output in C

Exercise:

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

Click Here to View the Solution!
#include <stdio.h>
int main() {
    FILE *fp;
    int c;
    // open the current input file
    fp = fopen(__FILE__,"r");
    do {
        c = getc(fp);    
        putchar(c);     
    }
    while(c != EOF);  // loop until the end of file is reached
    fclose(fp);
    return 0;
}
Click Here to View the Output!
/
 Welcome to GDB Online.
 GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
 C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
 Code, Compile, Run and Debug online from anywhere in world.
 */
 include 
 int main() {
     FILE *fp;
     int c;
     // open the current input file
     fp = fopen(FILE,"r");
     do {
         c = getc(fp);    
         putchar(c);     
     }
     while(c != EOF);  // loop until the end of file is reached
     fclose(fp);
     return 0;
 }
Click Here to View the Explanation!
  • This program is used to display its own source code as the program’s output.
  • In main(), a file pointer *fp and an integer variable c is created.
  • The current open input file is opened using a predefined macro of the name __FILE__ inside the fopen function and the reading mode as its parameters.
  • A do while loop is set which first reads the character in the file using getc and stores in the variable c and then displays the character using putchar.
  • The while loop is initialized which will continue its iterations until the end of the file is reached.
  • Finally, the file is closed using the fclose() function.

%d bloggers like this: