Display Source Code As Output C Program

By | August 5, 2017

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

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

int main()
      FILE *file_pointer;
      char ch;
      file_pointer = fopen("C:\Users\tusoni\Desktop\demo.c", "r");
      while (ch != EOF)
            ch = getc(file_pointer);
      return 0;

If you’re compiling this C program in Microsoft Windows operating system, you may get the following error:

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:

file_pointer = fopen("C:\\Users\\tusoni\\Desktop\\demo.c", "r");


C Program To Display Source Code As Output using File Pointers and print own source code

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.

Let's Discuss