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.
- #include <stdio.h>
- int main()
- {
- FILE *f;
- char c;
- f = fopen(__FILE__, "r");
- do
- {
- c = getc(f);
- putchar(c);
- }
- while(c != EOF);
- fclose(f);
- return 0;
- }
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
Post a Comment