Quick links
Write a C program to print source code of itself as output. How to print source code of itself as output in C programming.
Required knowledge
Basic Input Output, File Handling, Macros
How to print source code of itself using __FILE__
macro
Printing source code of a file is no complex. You should only bother about how to get path of current file without user input, rest is simple read and print file contents.
C programming supports various preprocessor directives (macros) for logging and exception handling. Macros such as
__FILE__
expands to path of current file.
__LINE__
expands to current line number where used.
__DATE__
expands to string pointing to today’s date.
__TIME__
expands to current time.
__FUNCTION__
expands to current function name where used. C99
To print source code of a program itself as output, you can use __FILE__
to get path of current file.
Program to print source code of itself as output
/**
* C program to print source code of itself as output
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fPtr;
char ch;
/*
* __FILE__ is a macro that contains path of current file.
* Open current program in read mode.
*/
fPtr = fopen(__FILE__, "r");
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_SUCCESS);
}
/* Read file character by character */
while ((ch = fgetc(fPtr)) != EOF)
{
printf("%c", ch);
}
/* Close files to release resources */
fclose(fPtr);
return 0;
}
Output
/** * C program to print source code of itself as output */ #include#include int main() { FILE *fPtr; char ch; /* * __FILE__ is a macro that contains path of current file. * Open current program in read mode. */ fPtr = fopen(__FILE__, "r"); /* fopen() return NULL if unable to open file in given mode. */ if (fPtr == NULL) { /* Unable to open file hence exit */ printf("\nUnable to open file.\n"); printf("Please check whether file exists and you have read privilege.\n"); exit(EXIT_SUCCESS); } /* Read file character by character */ while ((ch = fgetc(fPtr)) != EOF) { printf("%c", ch); } /* Close files to release resources */ fclose(fPtr); return 0; }
Happy coding 😉