선우의 코딩일지

C ) C 언어로 JAVA Systm.out.println 비슷하게 따라해보기! 본문

C

C ) C 언어로 JAVA Systm.out.println 비슷하게 따라해보기!

sunwookim05 2022. 8. 5. 15:48

오늘은 함수포인터를 사용해서 C 의 출력문을 비슷하게 구현 해보았다.

 

먼저 main.h 에 이렇게 소스코드를 작성한다.

#include <stdarg.h>

#ifndef _MAIN_H
#define _MAIN_H

#define null NULL
typedef enum{false, true} boolean;
typedef char *String;

void println(const String format, ...) {
    va_list ap;
    char buf[4096];
    va_start(ap, format);
    vsprintf(buf, format, ap);
    va_end(ap);
    fprintf(stdout, "%s\n", buf);
}

#pragma pack(push, 1)
typedef struct _System{
    struct _OUT_{
        void (*println)(const String, ...);
    }out;
}Sys;
#pragma pack(pop)

Sys System = {println};

#endif

메인문을 아래와 같이 작성한다.

 

 

#include <stdio.h>
#include "main.h"

int main(void){

    int a = 2;
    double b = 0.12;
    String str = "Hello World!";
    
    System.out.println("Hello World!");
    System.out.println("%d %lf", a, b);
    System.out.println(str);
	
    return 0;
}

출력

더보기

Hello World!

2 0.12

Hello World!

이렇게 println 을 구현 할 수있다.

Comments