首页  >  文章  >  后端开发  >  打印一个C程序本身的源代码

打印一个C程序本身的源代码

WBOY
WBOY转载
2023-08-29 17:05:07964浏览

打印一个C程序本身的源代码

给定的任务是打印编写的C程序本身。

我们必须编写一个C程序,它将打印自身。因此,我们可以在C中使用文件系统来打印我们编写代码的文件的内容,就像我们在“code 1.c”文件中编写代码一样,所以我们以读模式打开文件,并读取文件的所有内容,并将结果打印在输出屏幕上。

但是,在以读模式打开文件之前,我们必须知道我们正在编写代码的文件的名称。因此,我们可以使用“__FILE__”这个宏,默认情况下返回当前文件的路径。

“__FILE__”宏的示例

#include<stdio.h>
int main() {
   printf(&ldquo;%s&rdquo;, __FILE__);
}

上述程序将打印代码所在文件的源代码

宏__FILE__返回一个字符串,其中包含当前程序的路径,它被提及的位置。

因此,当我们将其合并到文件系统中以以只读模式打开代码所在的当前文件时,我们可以像这样做-

fopen(__FILE__, "r");

算法

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

示例

#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;
}

以上是打印一个C程序本身的源代码的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除