Google News
logo
C Program to Display its own Source Code as Output
In the following example of C program to display its own source code as output :
Program :
#include <stdio.h>

int main() {
    FILE *fp;
    char c;

    fp = fopen(__FILE__, "r");

    if (fp) {
        while ((c = getc(fp)) != EOF) {
            putchar(c);
        }

        fclose(fp);
    }

    return 0;
}
In this program, the __FILE__ macro expands to the name of the current source file.

We open the source file in read mode using fopen and then use getc to read the file character by character until the end of file is reached (EOF). We then use putchar to print each character to the console.

Note : This program will also display any comments or blank lines in the source code. If you want to exclude these, you could modify the program to check for them and skip them during the output.