卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章1829本站已运行4109

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

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

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

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

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

“__FILE__”宏的示例

#include<stdio.h>
int main() {
   printf(“%s”, __FILE__);
}

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

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

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

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

卓越飞翔博客
上一篇: python语言中%表示什么意思
下一篇: C程序打印所有ASCII值
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏