Friday, 10 January 2014

C Program to Display same Source Code as Output

Program :
#include<stdio.h>

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

    fp = fopen(__FILE__,"r");

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

    fclose(fp);

    return 0;
}
Output :
#include<stdio.h>

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

    fp = fopen(__FILE__,"r");

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

    fclose(fp);

    return 0;
}
Explanation :
fp = fopen(__FILE__,"r");
[arrowlist]
  • __FILE__ is Standard Predefined Macros in C Programming.
  • This macro will expand to the name of current file path.
  • Suppose we have saved this source code at path -
[/arrowlist]
c://tc/bin/file1.c
then
fp = fopen(__FILE__,"r");
will be expanded as -
fp = fopen("c://tc/bin/file1.c","r");

No comments:

Post a Comment