您好,欢迎访问一九零五行业门户网

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

给定的任务是打印编写的c程序本身。
我们必须编写一个c程序,它将打印自身。因此,我们可以在c中使用文件系统来打印我们编写代码的文件的内容,就像我们在“code 1.c”文件中编写代码一样,所以我们以读模式打开文件,并读取文件的所有内容,并将结果打印在输出屏幕上。
但是,在以读模式打开文件之前,我们必须知道我们正在编写代码的文件的名称。因此,我们可以使用“__file__”这个宏,默认情况下返回当前文件的路径。
“__file__”宏的示例
#include<stdio.h>int main() { printf(“%s”, __file__);}
上述程序将打印代码所在文件的源代码
宏__file__返回一个字符串,其中包含当前程序的路径,它被提及的位置。
因此,当我们将其合并到文件系统中以以只读模式打开代码所在的当前文件时,我们可以像这样做-
fopen(__file__, r);
算法startstep 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;}

以上就是打印一个c程序本身的源代码的详细内容。
其它类似信息

推荐信息