Skip to content
Related Articles

Related Articles

Improve Article

Printing source code of a C program itself

  • Difficulty Level : Medium
  • Last Updated : 11 Feb, 2018

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:




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

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.






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

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.

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.



My Personal Notes arrow_drop_up
Recommended Articles
Page :