English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C program displays its own source code as output

Comprehensive Collection of C Programming Examples

In this example, you will learn to use the __FILE__ macro to display the source code of the program.

To understand this example, you should understand the followingC programming languageTopic:

Although this problem looks complex, the concept of this program is very simple. Display the content of the file with the same source code as the written source code.

In C programming, there is a predefined macro __FILE__, which gives the name of the current input file.

#include <stdio.h>
int main() {
   //Locate the current input file.
   printf("%s", __FILE__);
}

C program displays its own source code

#include <stdio.h>
int main() {
    FILE *fp;
    int c;
   
    //Open the current input file
    fp = fopen(__FILE__, "r");
    do {
         c = getc(fp);   //Read character
         putchar(c);     //Display character
    }
    while(c != EOF);  //Loop until the end of the file is reached
    
    fclose(fp);
    return 0;
}

Comprehensive Collection of C Programming Examples