打印 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;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP