Let us understand how to display source code as output in C programming using a file pointer and fopen() method.
This C program seems complex to implement. But, if you apply a proper logic then, you can print the source code of a C program as its own output using file handling concepts in C programming.
All you need to do is to save your C program file and refer it in the fopen() method using reading mode.
Syntax of fopen() method
1 | fopen(source file location, mode) |
Note: This C program to display its own source code is compiled with CodeLite IDE and GNU GCC compiler on Microsoft Windows 10 operating system.
C Program To Display Source Code As Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include<stdio.h> int main() { FILE *file_pointer; char ch; file_pointer = fopen("C:\Users\tusoni\Desktop\demo.c", "r"); while (ch != EOF) { ch = getc(file_pointer); putchar(ch); } fclose(file_pointer); return 0; } |
If you’re compiling this C program in Microsoft Windows operating system, you may get the following error:
1 | error: incomplete universal character name \U |
To resolve this error, you will have to add escape characters. The backslash (\) is a special character and therefore, you must escape it by using escape sequence characters.
Please replace the above line with the following line:
1 | file_pointer = fopen("C:\\Users\\tusoni\\Desktop\\demo.c", "r"); |
Output

If you have any compilation errors or doubts about this C program to display its own source code, let us discuss it in the comment section below.