列印 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;
}

更新日期:2019-12-23

550 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告