Printing source of a C program itself


Given the task is to print the written C program itself.

We have to write a C program which will print itself. So, we can use file system in C to print the contents of the file of which we are writing the code, like we are writing the code in “code 1.c” file, so we open the file in the read mode and read all the contents of the file and print the results on the output screen.

But, before opening a file in read mode, we must know the name of the file we are writing code in. So, we can use “__FILE__” which is a macro and is by default, returns the path of the current file.

Example for the macro “__FILE__”

#include<stdio.h>
int main() {
   printf(“%s”, __FILE__);
}

The above program will print the source of the file in which the code is written

The macro __FILE__ returns a string with the path of the current program in which this macro is mentioned.

So, when we merge it into the file system to open the current file in which the code is in read mode, we do like −

fopen(__FILE__, “r”);

Algorithm

Start
Step 1-> In function int main(void)
   Declare a character c
   Open a FILE “file” “__FILE__” in read mode
   Loop do-while c != End Of File
      Set c = fgetc(file)
      putchar(c)
   Close the file “file”
Stop

Example

#include <stdio.h>
int main(void) {
   // to print the source code
   char c;
   // __FILE__ gets the location
   // of the current C program file
   FILE *file = fopen(__FILE__, "r");
   do {
      //printing the contents
      //of the file
      c = fgetc(file);
      putchar(c);
   }
   while (c != EOF);
   fclose(file);
   return 0;
}

Output

#include <stdio.h>
int main(void) {
   // to print the source code
   char c;
   // __FILE__ gets the location
   // of the current C program file
   FILE *file = fopen(__FILE__, "r");
   do {
      //printing the contents
      //of the file
      c = fgetc(file);
      putchar(c);
   }
   while (c != EOF);
   fclose(file);
   return 0;
}

Updated on: 23-Dec-2019

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements