C program to print its own source code



      The very first question asked in any IT company interview is this "You know about programming, so write a program or code to print its own source code". This question is asked frequently in every interview of any IT company. Today here is the program and its simplest explanation.


  1. #include <stdio.h>

  2. int main()
  3. {
  4. FILE *f;
  5. char c;

  6. f = fopen(__FILE__, "r");
  7. do
  8. {
  9.     c = getc(f);
  10.     putchar(c);
  11. }
  12. while(c != EOF);
  13. fclose(f);

  14. return 0;
  15. }
EXPLANATION:
  • Here you've created a file pointer named as f, which is used to access file and also you need a character or string which fetches data from file on your disk and print it on screen.
  • You can open current file in C language by fopen function with some necessary arguments. 
  • First argument(Line 8) required is a file name. __FILE__  is used to pass current file name and  second argument is mode in which you want to open a file(e.g. r for reading mode, w for writing mode, a for append mode).
  • Now(Line 9-14) you need a loop counter which reads and print every single character from the file till it reaches to the EOF(End Of File) character. 
  • Now Always remember to close the file you've opened previously. 

Comments

Popular Posts