Open In App

Printing source code of a C program itself

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Printing the source code of a C program itself is different from the Quine problem. Here we need to modify any C program in a way that it prints the whole source code. 

Approach

  1. Use predefined macro __FILE__ to get the location of the file.
  2. Open the source code file in reading mode and get the file pointer fptr. Check if the file is successfully opened or not.
  3. Read all the contents of the file using the do-while loop and fgetc.
  4. Close the file using the fclose function.

1. FILE Macro Method(Printing File Name)

We can use the concepts of file handling to print the source code of the program as output. The idea is to display the content from the same file you are writing the source code. The location of a C programming file is contained inside a predefined macro __FILE__.

Below is the C program to use __FILE__:

C




// C program to display the
// location of the file
#include <stdio.h>
 
// Driver code
int main()
{
   // Prints location of C this C code.
   printf("%s", __FILE__);
}


The output of the above program is the location of this C file. 

Output of the Program 1

Implementation

The following program displays the content of this particular C file(source code) because __FILE__ contains the location of this C file in a string. 

2. Display the Program

C




// C program that prints its source code.
#include<stdio.h>
  
// Driver code
int main(void)
{
    // We can append this code to any C program
    // such that it prints its source code.
    char c;
    FILE *fp = fopen(__FILE__, "r");
  
    do
    {
        c = fgetc(fp);
        putchar(c);
    }
    while (c != EOF);
  
    fclose(fp);
  
    return 0;
}


Output:

Output of the Program

Note: The above program may not work online compiler as fopen might be blocked.



Last Updated : 26 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads