Printing source code of a C program itself

How to print source code of a C program itself? Note this is different from Quine problem. Here we need to modify any C program in a way that it prints whole source code.

Explanation :
We can use the concepts of file handling to print the source code of the program as output. The idea being : displaying the content from the same file you are writing the source code.

The location of a C programming file is contained inside a predefined macro __FILE__. For example:

filter_none

edit
close

play_arrow

link
brightness_4
code

   
#include <stdio.h>
int main()
{
   // Prints location of C this C code.
   printf("%s",__FILE__);
}

chevron_right


The output of the above program is the location of this C file.
The following program displays the content of this particular C file(source code) because __FILE__ contains the location of this C file in a string.

filter_none

edit
close

play_arrow

link
brightness_4
code

   
// A C program that prints its source code.
#include <stdio.h>
   
int main(void)
{
    // We can append this code to any C program
    // such that it prints its source code.
  
    char c; 
    FILE *fp = fopen(__FILE__, "r");
   
    do
    {
        c = fgetc(fp);
        putchar(c);
    }
    while (c != EOF);
   
    fclose(fp);
   
    return 0;
}

chevron_right


Output :

// A C program that prints its source code.
#include <stdio.h>
 
int main(void)
{
    // We can append this code to any C program
    // such that it prints its source code.

    char c; 
    FILE *fp = fopen(__FILE__, "r");
 
    do
    {
        c = fgetc(fp);
        putchar(c);
    }
    while (c != EOF);
 
    fclose(fp);
 
    return 0;
}

Note : The above program may not work online compiler as fopen might be blocked.

This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.