write a c program which produces its own source code as its output






How do you write a program which produces its own source code as its output in c language?

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










1. Write a c program to convert decimal number to hexadecimal number.
3. Write a c program to convert octal number to decimal number.
4. Write a c program to convert octal number to hexadecimal number.
5. Write a c program to convert hexadecimal number to decimal number.
6. Write a c program to convert hexadecimal number to octal number.
8. Write a c program to convert binary number to hexadecimal number.
9. Write a c program to convert binary number to octal number.
11. Write a c program to convert hexadecimal number to binary number.
12. Write a c program to convert octal number to binary number.
14. Write a c program to convert centigrade to fahrenheit.

9 comments:

  1. The __FILE__ macro expands to full path of the current input file.
    So, in the program __FILE__ is replaced by the path of the program.
    Then we simply read from the file and display it.

    ReplyDelete
  2. thnx....:):):)


    excellent answer...:)

    ReplyDelete
  3. Thanks a lot ....

    ReplyDelete
  4. very good answer

    ReplyDelete
  5. the above wont run if the source file is deleted.. but this will

    char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}

    ReplyDelete
  6. very nice

    ReplyDelete
  7. char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}

    Hey Boddy Can you explain the line?
    How it works?
    Advance Thank you.

    ReplyDelete