C Example for Beginners: C Program to Display its own Source Code as Output

(C programming Example for Beginners)

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, the concept behind this program is straightforward; display the content from the same file you are writing the source code.

Procedure to display its own source code in C programming
#include <stdio.h>
int main() {

   // location the current input file.
   printf("%s",__FILE__);
}

C program to display its own source code


#include <stdio.h>
int main(){
    FILE *fp;
    int c;
   
    // open the current input file
    fp = fopen(__FILE__,"r");

    do {
         c = getc(fp);   // read character 
         putchar(c);     // display character
    }
    while(c != EOF);  // loop until the end of file is reached
    
    fclose(fp);
    return 0;
}

 

 

C Example for Beginners: C Program to Display its own Source Code as Output

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.