首頁  >  文章  >  後端開發  >  列印一個C程式本身的原始碼

列印一個C程式本身的原始碼

WBOY
WBOY轉載
2023-08-29 17:05:07964瀏覽

列印一個C程式本身的原始碼

給定的任務是列印編寫的C程式本身。

我們必須寫一個C程序,它將列印自身。因此,我們可以在C中使用檔案系統來列印我們編寫程式碼的檔案的內容,就像我們在「code 1.c」檔案中編寫程式碼一樣,所以我們以讀取模式開啟文件,並讀取檔案的所有內容,並將結果列印在輸出畫面上。

但是,在以讀取模式開啟檔案之前,我們必須知道我們正在編寫程式碼的檔案的名稱。因此,我們可以使用「__FILE__」這個宏,預設會傳回目前檔案的路徑。

「__FILE__」巨集的範例

#include<stdio.h>
int main() {
   printf(&ldquo;%s&rdquo;, __FILE__);
}

上述程式將列印程式碼所在檔案的原始程式碼

巨集__FILE__傳回字串,其中包含目前程式的路徑,它被提及的位置。

因此,當我們將其合併到檔案系統中以唯讀模式開啟程式碼所在的目前檔案時,我們可以像這樣做-

fopen(__FILE__, "r") ;

演算法

Start
Step 1-> In function int main(void)
   Declare a character c
   Open a FILE &ldquo;file&rdquo; &ldquo;__FILE__&rdquo; in read mode
   Loop do-while c != End Of File
      Set c = fgetc(file)
      putchar(c)
   Close the file &ldquo;file&rdquo;
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程式本身的原始碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除