Like us on google+

Tuesday, 22 October 2013

Widgets

C PROGRAM WHICH PRINTS ITS OWN SOURCE CODE AS ITS OUTPUT.

Programs statement sounds to be scary but one thing is sure after reading this post you wont feel so.  
*****************************************************************
#include<stdio.h>

int main(){
    FILE *fpt;
    char c;

    fpt = fopen(__FILE__,"r");
  do{
         c= getc(fpt);
         putchar(c);
    }
    while(c!=EOF);

    fclose(fpt);
   
    return 0;
}
--------------------------------------------------
Sample output:
#include<stdio.h>

int main(){
    FILE *fpt;
    char c;

    fpt = fopen(__FILE__,"r");

    do{
         c= getc(fpt);
         putchar(c);
    }
    while(c!=EOF);

    fclose(fpt);

    return 0;
}
***************************************************
Description: 
fopen() function is used to open an existing
file or else to create a new file. 

Syntax of fopen() function call is:
FILE *fopen(const char* filename,const char mode);
filename is string and mode specifies how the file is to be opened i.e in write mode,read mode ...etc 

In the above program _FILE_ which is used as filename inside function fopen(__FILE__,"r");  is macro which is replaced by the path of the program and r inside fopen(__FILE__,"r"); specifies its opened in read mode.

getc() function returns the next character from the specified file.
Then contents of the file gets printed using putchar(c) which is used inside the do while loop. Whenever the EOF is encountered control comes outside the loop and file is closed  by using function fclose(fpt);

I hope this post was helpful...


SHARE THIS POST   

  • Facebook
  • Twitter
  • Myspace
  • Google Buzz
  • Reddit
  • Stumnleupon
  • Delicious
  • Digg
  • Technorati
About us:
Hi guys Sandesh and Rajesh here ... studing engineering in PESIT started this blog as a google contest and also we love blogging ...Hope u like it ...Encourage us by liking us on g+... Any queries dont hesitate to ask Read More →

1 comments: