February 01, 2015

C Program that prints its own Source Code | C Programming Quine

05:25 Posted by DurgaSwaroop No comments
Quine in programming terms is a program which outputs its own Source code. These are self-replicating programs and are very popular in the programming community. So, in this article we will see how we can achieve this.
           This problem may sound complex, but this is actually quite easy and simple. So, the way we proceed with this is by opening the source file from the program and print out each and every character.
Sounds simple, doesn't it? Lets code it.
Things you need to know for this : Usage of File Pointers
C Programming - Swaroop's Blog
Procedure: Lets break down the approach step by step
  1. Open the current file (fopen()) using a file pointer (in Read Mode)
  2. Read characters one after the other and print them until you reach the end of the file (EOF)
  3. Close the file
To open the file we'll use the fopen() function which takes in two parameters, the location of the file and mode of opening (Read/Write). Fortunately for us, there is a macro in C, to give us file's location, called  _FILE_  macro. Using this we can get the location/path of the current file.

So, if you execute the following statement, the output will be the location as shown

Output: C:\Users\DSP\Desktop\selfProgram.c
Now, you know everything there is to know about this. So, let's write the program.
#include <stdio.h>
    FILE *fp; // file pointer declaration
    char c;   // variable to store the characters from the file
    fp = fopen(__FILE__,"r");  // opens the file in Read mode
                       // Location argument specified by _FILE_ macro           
        c = fgetc(fp); //read a character and store in c
        putchar(c);       // print the char on to the screen
    while(c!=EOF);       // continue till we reach End Of File

    fclose(fp);        // close the file to avoid file corruption 
And, the output as you can expect will be the same as shown.

So, That is all for this article. If you like this article you might like our other articles too about Programming. So, check them out. Also stay tuned for a lot of other interesting articles.

As, always, Have a happy reading and Stay Awesome !

Follow our blog posts @ Follow. So that you won't miss any interesting post and also to be the first to know the answers to many interesting questions.
Follow us on our Facebook  page @ Fre Blogg 
Head over to my You Tube channel for a lot of interesting tutorials @ You Tube


Post a comment

Please Enter your comment here......