กำหนดให้งานคือพิมพ์โปรแกรมภาษาซีที่เขียนเอง
เราต้องเขียนโปรแกรม 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;
}