C语言将其自身源代码作为输出打印的程序

要理解这个示例,您应该了解以下 C 编程 主题


尽管这个问题看起来很复杂,但这个程序的根本概念很简单;显示来自你编写源代码的同一文件中的内容。

Procedure to display its own source code in C programming

在C编程中,有一个名为__FILE__的预定义宏,它给出了当前输入文件的名称。

#include <stdio.h>
int main() {

   // location the current input file.
   printf("%s",__FILE__);
}

C程序显示自己的源代码

#include <stdio.h>
int main() {
    FILE *fp;
    int c;
   
    // open the current input file
    fp = fopen(__FILE__,"r");

    do {
         c = getc(fp);   // read character 
         putchar(c);     // display character
    }
    while(c != EOF);  // loop until the end of file is reached
    
    fclose(fp);
    return 0;
}
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战