Home > Backend Development > C++ > body text

Print the source code of a C program itself

WBOY
Release: 2023-08-29 17:05:07
forward
1019 people have browsed it

Print the source code of a C program itself

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(&ldquo;%s&rdquo;, __FILE__);
}
Copy after login

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") ;

Algorithm

Start
Step 1-> In function int main(void)
   Declare a character c
   Open a FILE &ldquo;file&rdquo; &ldquo;__FILE__&rdquo; in read mode
   Loop do-while c != End Of File
      Set c = fgetc(file)
      putchar(c)
   Close the file &ldquo;file&rdquo;
Stop
Copy after login

Example

#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;
}
Copy after login
Copy after login

Output

#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;
}
Copy after login
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template