今天面试,被问到如何用C语言实现一个能打印自身源代码的程序,且程序不能访问之前的源代码的文件。说了一些思路,回来后发现思路有问题,只好在机器上尝试。以下是一个种可行的实现方法,源码如下:
#include <stdio.h>
#define LINE_MAX_NUM 1024
int main()
{
char buf[LINE_MAX_NUM] = {0};
FILE *file = fopen(__FILE__, "r");
if (file == NULL)
{
printf("file not found!\n");
return -1;
}
/*
other code goes here .....
....................................
....................................
*/
while(fgets(buf, LINE_MAX_NUM, file) != NULL)
{
printf("%s", buf);
}
fclose(file);
return 0;
}
运行结果如下:
liliang@server:/home/smp311$ ./a.out
#include <stdio.h>
#define LINE_MAX_NUM 1024
int main()
{
char buf[LINE_MAX_NUM] = {0};
FILE *file = fopen(__FILE__, "r");
if (file == NULL)