The given task is to print the written C program itself.
We have to write a C program that will print itself. So, we can use the file system in C to print the contents of the file we write code in, just like we wrote the code in the "code 1.c" file, so we open the file in read mode and read all of the file content and print the results on the output screen.
However, before opening a file in read mode, we must know the name of the file we are writing code for. Therefore, we can use the "__FILE__" macro, which returns the path of the current file by default.
Example of "__FILE__" macro
#include<stdio.h> int main() { printf(“%s”, __FILE__); }
The above program will print the source code of the file where the code is located
Macro __FILE__ returns a string, It contains the path of the current program, where it is mentioned.
So when we merge it into the file system to open the current file where the code is in read-only mode, we can do something like this -
fopen(__FILE__, "r") ;
Start Step 1-> In function int main(void) Declare a character c Open a FILE “file” “__FILE__” in read mode Loop do-while c != End Of File Set c = fgetc(file) putchar(c) Close the file “file” Stop
#include <stdio.h> int main(void) { // to print the source code char c; // __FILE__ gets the location // of the current C program file FILE *file = fopen(__FILE__, "r"); do { //printing the contents //of the file c = fgetc(file); putchar(c); } while (c != EOF); fclose(file); return 0; }
#include <stdio.h> int main(void) { // to print the source code char c; // __FILE__ gets the location // of the current C program file FILE *file = fopen(__FILE__, "r"); do { //printing the contents //of the file c = fgetc(file); putchar(c); } while (c != EOF); fclose(file); return 0; }
The above is the detailed content of Print the source code of a C program itself. For more information, please follow other related articles on the PHP Chinese website!