今天面試,被問到如何用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)
{
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
file not found!
分析一下原因,原來在源代碼中的__FILE__被替換爲源代碼在系統上所在的路徑,當源代碼文件所在的位置改變時,便無法找到。何爲正解?看來要達到最初的目的,需要將源代碼所在的文件包含在生成的可執行文件中才能從更本上解決問題。如何才能辦到? 繼續探索中....