C program to display its own source code

C program to display its own source code as output

This article explains how you can write a C program to display its own source code. It also explains logic to print source code of a C program itself. You should have basic knowledge of file handling in C to write C program to print source code of itself as output.

There is a predefined macro  __FILE__  in C language. It contains the location of a C programming file, it is working on.

For example:

#include <stdio.h>
int main()
{
    printf("\n%s\n",__FILE__);
}

Output:  This C program print the location of the C programming file.

__FILE__

 

Some C Predefined Macros

 

Macro    Description

__DATE__	 current date in "MM DD YYYY" format.
__TIME__	 current time in "HH:MM:SS" format.
__FILE__	 current file name.
__LINE__	 current line number.
__FUNCTION__ expands to the current function name where used. C99

 

Read this article,  C macros, you should know.

 

How to print source code itself using __FILE__  (Predefined macro)

 

Printing the code itself as an output on console is easy, you just have basic knowledge of C file handling. There are a few steps to write C program to display its own source code

  • Get the file location using the predefined macro __FILE__.
  • Open the source file in reading mode and get the file pointer in fptr. Also, check that file has been open successfully or not.
  • Read all contents of the file using the fgetc in C and do while loop.
  • In the last close the file using the fclose function.

 

#include <stdio.h>
#include<stdlib.h>

int main()
{
    //file pointer
    FILE *fp = NULL;
    int ch = 0;
    //open the file
    fp = fopen(__FILE__, "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }
    //read till EOF
    do
    {
        ch = fgetc(fp);
        printf("%c",ch);
    }
    while (ch != EOF);

    //close open file
    fclose (fp);

    return 0;
}

Output:

Printing the code itself as an output on console

Code Analysis:

In the above c example, first, I am opening the source file in reading mode using the __FILE__ (pre-defined macro). If source file opened successfully in read mode ( “r”), get the file pointer.Using the if condition I am verifying that file is created successfully or not.

//open the file
fp = fopen(__FILE__, "r");
if(fp == NULL)
{
    printf("Error in opening the file\n");
    exit(1);
}

After opening the file successfully, I am using fgetc function to read all contents of the source file and display it on the console screen. Using the do-while loop I am confirming that all data will read.

//read till EOF
  do
  {
      ch = fgetc(fp);
      printf("%c",ch);
  }
  while (ch != EOF);

 

In the last, I am calling fclose function to close the open-source file.

//close open file
    fclose (fp);

 

Recommended posts: