Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 프로그램 자체의 인쇄 소스

<시간/>

주어진 작업은 작성된 C 프로그램 자체를 인쇄하는 것입니다.

우리는 스스로 인쇄할 C 프로그램을 작성해야 합니다. 따라서 "code 1.c" 파일에 코드를 작성하는 것처럼 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;
}