Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Printing source of a C program itself
In C programming, a self-printing program (also called a quine) is a program that prints its own source code as output. This can be achieved using the __FILE__ macro along with file I/O operations to read and display the current source file.
Syntax
FILE *fopen(__FILE__, "r");
The __FILE__ macro is a preprocessor macro that returns the name of the current source file as a string literal. This allows us to open and read our own source code at runtime.
Example: Understanding __FILE__ Macro
First, let's see how the __FILE__ macro works −
#include <stdio.h>
int main() {
printf("Current file: %s<br>", __FILE__);
return 0;
}
Current file: main.c
Example: Complete Self-Printing Program
Now let's create a program that prints its entire source code −
Note: This example uses file operations and will work when compiled and run locally. Online compilers may have limitations with file access.
#include <stdio.h>
int main(void) {
char c;
FILE *file = fopen(__FILE__, "r");
if (file == NULL) {
printf("Error: Cannot open source file<br>");
return 1;
}
while ((c = fgetc(file)) != EOF) {
putchar(c);
}
fclose(file);
return 0;
}
How It Works
- The
__FILE__macro expands to the current source file name at compile time -
fopen(__FILE__, "r")opens the source file in read mode -
fgetc()reads characters one by one from the file -
putchar()prints each character to the console - The loop continues until EOF (End of File) is reached
Key Points
- Always check if
fopen()returns NULL to handle file opening errors - Use
fclose()to properly close the file after reading - The program reads its own source code character by character and prints it exactly
- This technique works because the executable knows the path to its source file
Conclusion
Self-printing programs in C demonstrate the power of the __FILE__ macro and file I/O operations. While mainly used for educational purposes, they showcase how programs can access and manipulate their own source code at runtime.
