'글나무'에 해당되는 글 101건

  1. 2018.10.05 날짜 관련 함수
  2. 2017.08.25 std::regx
  3. 2015.06.11 doxygen 탬플릿
  4. 2014.12.30 Image지원되는 RTF Editor입니다.
  5. 2013.08.08 VS 2008 원격 디버깅하다가 삽질기..
  6. 2013.07.01 RIFF AVI 파일 헤더 분석
  7. 2013.01.03 ReBar 컨트롤에 넣을때 구현해야할 윈도우 메세지
  8. 2012.06.14 윈도우 시간 로컬 문자열로 변환
  9. 2012.02.15 오랜만에 다시 공부해서 만들어본 메이크파일
  10. 2011.08.10 유한상태기계 (FSM:Finite State Machine) C++ Sample 1
  11. 2011.06.16 멤버함수 테이블로 호출 하기
  12. 2011.04.25 std::for_each()를 이용한 포인터 삭제
  13. 2011.04.15 TortoiseSVN 사용할 떄 VS 중간파일 제외시키기 & SVN 파일 삭제하기
  14. 2011.03.30 #pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console") 대신 쓸만한 것
  15. 2011.03.25 가끔은 C++캐스팅 연산자 쓰자! -_-;
  16. 2011.03.18 Windows Sleep(1)은 1 msec을 안 놀아주고 약 10 msec를 놀아 준다.
  17. 2011.01.04 sntp source입니다.
  18. 2010.10.27 EXCEL EXPORT
  19. 2010.10.18 WTL에서 FormView Scroll하기
  20. 2010.10.18 WTL 각 종 View 기본 Template Code
  21. 2010.09.07 STL allocator 기본 형식
  22. 2010.08.19 MSVC에서 Code에서 링커 옵션 주기
  23. 2010.05.12 web에서 주어온 string function code
  24. 2010.05.12 회사 아저씨가 sprintf쓸때 parameter 하나로 쓰고 싶다고 해서 만들어본 code
  25. 2010.03.16 setjmp()/longjmp()을 이용한 Signal Handling시 유의 할점
  26. 2010.03.16 Explicit template instantiation
  27. 2010.03.09 복사 연산 Class
  28. 2009.12.30 심각하게 공감간다..
  29. 2009.11.27 GetRemovableDrives()
  30. 2009.10.23 MS-SQL 저장 Procedure - Data 추가시 Table이 없으면 자동으로 추가

 

#include "stdafx.h"

#include <time.h>

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

namespace cx

{

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

typedef void* pointer_t; // 4 bytes

 

//===========================================================================

typedef signed   int int_t ;

typedef unsigned int uint_t;

 

typedef signed             char int8_t  ; //                       -127 ~ +128

typedef signed   short     int  int16_t ; //                    -32,768 ~ +32,767

typedef signed   long      int  int32_t ; //             -2,147,483,648 ~ +2,147,483,647

typedef signed   long long int  int64_t ; // -9,223,372,036,854,775,808 ~ +9,223,372,036,854,775,807

typedef unsigned           char uint8_t ; // 0 ~ 255

typedef unsigned short     int  uint16_t; // 0 ~ 65,535

typedef unsigned long      int  uint32_t; // 0 ~ 4,294,967,295

typedef unsigned long long int  uint64_t; // 0 ~ 18,446,744,073,709,551,615

 

 

typedef bool bool_t;

 

typedef ::time_t time_t;

 

typedef unsigned char byte_t;

 

}

 

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

/*

 

# Julian Period

15 (indiction cycle) × 19 (Metonic cycle) × 28 (Solar cycle) = 7980 years

첫 주기 : 4713 BC ~ AD 3268

 

# Julian Day

Julian Period의 일

천문학에서 사용

Julian Calendar 와는 다른 별도의 개념

 

# Julian Day Number(JDN)

정수 형태의 Julian

-4712/01/01 = 0(BC 4713)

-4712/01/02 = 1

-4712/01/03 = 2

JDN은 날짜 의미로만 사용

 

# Julian Date(JD)

실수 형태의 Julian

-4712/01/01 12:00:00 = 0.0

-4712/01/02 00:00:00 = 0.5

-4712/01/02 12:00:00 = 1.0

-4712/01/03 00:00:00 = 1.5

-4712/01/03 12:00:00 = 2.0

JD는 날짜+시간 의미 사용

 

# Julian Calendar

1582 10 04일 목요일 까지 사용

 

# Gregorian Calendar

1582 10 15일 금요일 부터 사용

 

# Calendar Date

1582 10 05 ~ 1582 10 14일은 존재 안함

 

# Unix Epoch Time

1970 01 01

윤초 없음

 

# 윤초

GMT 12 31 23:59:60 - 한국시간 01 01일 오전 08 59 60

GMT 06 30 23:59:60 - 한국시간 07 01일 오전 08 59 60

필요시 삽입됨

 

# Epoch Time

윤초 표시하지 않음

 

# 참고 URL

https://en.wikipedia.org/wiki/Julian_day

 

http://aa.usno.navy.mil/data/docs/JulianDate.php

https://www.tondering.dk/claus/cal/gregorian.php#country

http://jidolstar.tistory.com/482

 

*/

 

 

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

void jdn_to_modified_jdn        (cx::int_t jdn, cx::int_t& modified_jdn);

void jdn_to_truncated_jd        (cx::int_t jdn, cx::int_t& truncated_jd);

void jdn_to_lilian_date         (cx::int_t jdn, cx::int_t& lilian_date);

void jdn_to_unix_time_day_count (cx::int_t jdn, cx::int_t& unix_time_day_count);

 

//===========================================================================

void gregorian_calendar_date_to_jdn (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t& jdn);

void julian_calendar_date_to_jdn    (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t& jdn);

void jdn_to_gregorian_calendar_date (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day);

void jdn_to_julian_calendar_date    (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day);

 

//===========================================================================

cx::int_t  calendar_date_from_1582_10_05_to_1582_10_14 (cx::int_t year, cx::int_t month, cx::int_t day);

 

cx::bool_t calendar_date_to_jdn (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t& jdn);

void       jdn_to_calendar_date (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day);

 

//===========================================================================

cx::int_t us_get_day_of_week  (cx::int_t jdn);

cx::int_t iso_get_day_of_week (cx::int_t jdn);

 

//===========================================================================

cx::bool_t gregorian_calendar_is_leap_year          (cx::int_t year);

cx::bool_t gregorian_calendar_get_last_day_of_month (cx::int_t year, cx::int_t month, cx::int_t& day);

cx::bool_t gregorian_calendar_is_valid_date         (cx::int_t year, cx::int_t month, cx::int_t day);

 

//===========================================================================

void epoch_to_jdn         (cx::int_t base_epoch_jdn, cx::int_t day_number, cx::int_t& jdn);

void epoch_to_date        (cx::int_t base_epoch_jdn, cx::int_t day_number, cx::int_t& year, cx::int_t& month, cx::int_t& day);

void epoch_to_day_of_week (cx::int_t base_epoch_jdn, cx::int_t day_number, cx::int_t& day_of_week);

void epoch_to_time        (                          cx::int_t daysecond_number, cx::int_t& hour, cx::int_t& minute, cx::int_t& second);

 

//===========================================================================

cx::int_t epoch_second_get_day_number       (cx::time_t epoch_second);

cx::int_t epoch_second_get_daysecond_number (cx::time_t epoch_second);

 

void epoch_second_to_jdn         (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& jdn);

void epoch_second_to_datetime    (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& year, cx::int_t& month, cx::int_t& day, cx::int_t& day_of_week, cx::int_t& hour, cx::int_t& minute, cx::int_t& second);

void epoch_second_to_date        (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& year, cx::int_t& month, cx::int_t& day);

void epoch_second_to_day_of_week (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& day_of_week);

void epoch_second_to_time        (                          cx::time_t epoch_second, cx::int_t& hour, cx::int_t& minute, cx::int_t& second);

void datetime_to_epoch_second    (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t hour, cx::int_t minute, cx::int_t second, cx::int_t base_epoch_jdn, cx::time_t& epoch_second);

 

//===========================================================================

cx::int_t unix_time_get_base_epoch_jdn (void);

 

void unix_time_to_jdn         (cx::time_t t, cx::int_t& jdn);

void unix_time_to_datetime    (cx::time_t t, cx::int_t& year, cx::int_t& month, cx::int_t& day, cx::int_t& day_of_week, cx::int_t& hour, cx::int_t& minute, cx::int_t& second);

void unix_time_to_date        (cx::time_t t, cx::int_t& year, cx::int_t& month, cx::int_t& day);

void unix_time_to_day_of_week (cx::time_t t, cx::int_t& day_of_week);

void unix_time_to_time        (cx::time_t t, cx::int_t& hour, cx::int_t& minute, cx::int_t& second);

void datetime_to_unix_time    (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t hour, cx::int_t minute, cx::int_t second, cx::time_t& t);

 

 

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

void jdn_to_modified_jdn (cx::int_t jdn, cx::int_t& modified_jdn)

{

         /*

         # Modified JD

        

         Epoch:       0h Nov 17, 1858

         Calculation: JD 2400000.5

         */

 

         modified_jdn = jdn-2400001;

}

 

void jdn_to_truncated_jd (cx::int_t jdn, cx::int_t& truncated_jd)

{

         /*

         # Truncated JD

        

         Introduced by NASA in 1979

        

         Epoch:       0h May 24, 1968

         Calculation: floor (JD 2440000.5)

 

         cf:

         ceil () 소수점 이하 올림

         floor() 소수점 이하 버림

         round() 소수점 반올림

         */

 

         truncated_jd = jdn-2440001;

}

 

void jdn_to_lilian_date (cx::int_t jdn, cx::int_t& lilian_date)

{

         /*

         # Lilian date

 

         Count of days of the Gregorian calendar

        

         Epoch:       Oct 15, 1582

         Calculation: floor (JD 2299159.5)

         */

 

         lilian_date = jdn-2299160;

}

 

void jdn_to_unix_time_day_count (cx::int_t jdn, cx::int_t& unix_time_day_count)

{

         /*

         # Unix Time

 

         Count of seconds

 

         Epoch:       0h Jan 1, 1970

         Calculation: (JD 2440587.5) × 86400

         */

 

         unix_time_day_count = jdn-2440588;

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

// Converting Gregorian calendar date to Julian Day Number(noon)

void gregorian_calendar_date_to_jdn (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t& jdn)

{

         // The algorithm is valid for all (possibly proleptic) Gregorian calendar dates after November 23, -4713.

 

         cx::int_t J;

         cx::int_t Y;

         cx::int_t M;

         cx::int_t D;

 

 

         Y = year;

         M = month;

         D = day;

 

        

         cx::int_t M1;

         cx::int_t Y1;

 

 

         M1 = (M - 14) / 12;

         Y1 = Y + 4800;

         J  = 1461 * (Y1 + M1) / 4 + 367 * (M - 2 - 12 * M1) / 12 - (3 * ((Y1 + M1 +100) / 100)) / 4 + D - 32075;

 

 

         jdn = J;

}

 

// Converting Julian calendar date to Julian Day Number(noon)

void julian_calendar_date_to_jdn (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t& jdn)

{

         // The algorithm is valid for all (possibly proleptic) Julian calendar years >= -4712, that is, for all JDN >= 0.

 

         cx::int_t J;

         cx::int_t Y;

         cx::int_t M;

         cx::int_t D;

 

 

         Y = year;

         M = month;

         D = day;

 

         J = 367 * Y - (7 * (Y + 5001 + (M - 9) / 7)) / 4 + (275 * M) / 9 + D + 1729777;

 

 

         jdn = J;

}

 

#if 0

void jdn_to_gregorian_calendar_date (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         cx::int_t J;

         cx::int_t Y;

         cx::int_t M;

         cx::int_t D;

 

        

         J = jdn;

 

 

         cx::int_t p;

         cx::int_t q;

         cx::int_t r;

         cx::int_t s;

         cx::int_t t;

         cx::int_t u;

         cx::int_t v;

 

 

         p = J + 68569;

         q = 4*p/146097;

         r = p - (146097*q + 3)/4;

         s = 4000*(r+1)/1461001;

         t = r - 1461*s/4 + 31;

         u = 80*t/2447;

         v = u/11;

 

         Y = 100*(q-49)+s+v;

         M = u + 2 - 12*v;

         D = t - 2447*u/80;

 

         year  = Y;

         month = M;

         day   = D;

}

#endif

 

void jdn_to_gregorian_calendar_date (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         const cx::int_t y = 4716;

         const cx::int_t j = 1401;

         const cx::int_t m = 2;

         const cx::int_t n = 12;

         const cx::int_t r = 4;

         const cx::int_t p = 1461;

         const cx::int_t v = 3;

         const cx::int_t u = 5;

         const cx::int_t s = 153;

         const cx::int_t w = 2;

         const cx::int_t B = 274277;

         const cx::int_t C = -38;

 

         cx::int_t J;

         cx::int_t Y;

         cx::int_t M;

         cx::int_t D;

 

 

         J = jdn;

 

 

         cx::int_t f;

         cx::int_t e;

         cx::int_t g;

         cx::int_t h;

 

         f = J + j + (((4 * J + B) / 146097) * 3) / 4 + C;

         e = r * f + v;

         g = (e % p) / r;

         h = u * g + w;

        

         D = (h % s) / u  + 1;

         M = (h / s + m) % n + 1;

         Y = (e / p) - y + (n + m - M) / n;

 

 

         year  = Y;

         month = M;

         day   = D;

}

 

void jdn_to_julian_calendar_date (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         const cx::int_t y = 4716;

         const cx::int_t j = 1401;

         const cx::int_t m = 2;

         const cx::int_t n = 12;

         const cx::int_t r = 4;

         const cx::int_t p = 1461;

         const cx::int_t v = 3;

         const cx::int_t u = 5;

         const cx::int_t s = 153;

         const cx::int_t w = 2;

         const cx::int_t B = 274277;

         const cx::int_t C = -38;

 

 

         cx::int_t J;

         cx::int_t Y;

         cx::int_t M;

         cx::int_t D;

 

 

         J = jdn;

 

 

         cx::int_t f;

         cx::int_t e;

         cx::int_t g;

         cx::int_t h;

 

         f = J + j;

         e = r * f + v;

         g = (e % p) / r;

         h = u * g + w;

        

         D = (h % s) / u  + 1;

         M = (h / s + m) % n + 1;

         Y = (e / p) - y + (n + m - M) / n;

 

 

         year  = Y;

         month = M;

         day   = D;

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

cx::int_t calendar_date_from_1582_10_05_to_1582_10_14 (cx::int_t year, cx::int_t month, cx::int_t day)

{

         cx::int_t from_1582_10_05_to_1582_10_14;

 

 

 

         from_1582_10_05_to_1582_10_14 = 0;

         if     (year< 1582)

         {

                  from_1582_10_05_to_1582_10_14 = -1;

         }

         else if (year==1582)

         {

                  if      (month <  10)

                  {

                           from_1582_10_05_to_1582_10_14 = -1;

                  }

                  else if (month == 10)

                  {

                           if      (day <= 4)

                           {

                                   from_1582_10_05_to_1582_10_14 = -1;

                           }

                           else if (day >= 15)

                           {

                                   from_1582_10_05_to_1582_10_14 = 1;

                           }

                  }

                  else if (month >  10)

                  {

                           from_1582_10_05_to_1582_10_14 = 1;

                  }

         }

         else if (year> 1582)

         {

                  from_1582_10_05_to_1582_10_14 = 1;

         }

 

 

         return from_1582_10_05_to_1582_10_14;

}

 

cx::bool_t calendar_date_to_jdn (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t& jdn)

{

         cx::int_t from_1582_10_05_to_1582_10_14;

 

 

 

         from_1582_10_05_to_1582_10_14 = calendar_date_from_1582_10_05_to_1582_10_14(year,month,day);

 

         if      (0> from_1582_10_05_to_1582_10_14)

         {

                  julian_calendar_date_to_jdn    (year,month,day, jdn);

         }

         else if (0==from_1582_10_05_to_1582_10_14)

         {

                  return false;

         }

         else if (0< from_1582_10_05_to_1582_10_14)

         {

                  gregorian_calendar_date_to_jdn (year,month,day, jdn);

         }

 

         return true;

}

 

void jdn_to_calendar_date (cx::int_t jdn, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         // jdn: 2299160 = 1582-10-04 Julian Calendar Date

         // jdn: 2299161 = 1582-10-15 Gregorian Calendar Date

 

         if (jdn<=2299160)

         {

                  jdn_to_julian_calendar_date    (jdn, year,month,day);

         }

         else

         {

                  jdn_to_gregorian_calendar_date (jdn, year,month,day);

         }

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

cx::int_t us_get_day_of_week (cx::int_t jdn)

{

         /*

         W1 = mod(J + 1, 7)

 

         0=Sun

         1=Mon

         2=Tue

         3=Wed

         4=Thu

         5=Fri

         6=Sat

         */

 

         return (jdn + 1) % 7;

}

 

cx::int_t iso_get_day_of_week (cx::int_t jdn)

{

         /*

         W0 = mod (J, 7) + 1

 

         1=Mon

         2=Tue

         3=Wed

         4=Thu

         5=Fri

         6=Sat

         7=Sun

         */

 

         return (jdn % 7) + 1;

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

cx::bool_t gregorian_calendar_is_leap_year (cx::int_t year)

{

         if ( (0==(year%400))

              ||

              (0!=(year%100) && 0==(year%4)) )

         {

                  return true;

         }

 

         return false;

}

 

cx::bool_t gregorian_calendar_get_last_day_of_month (cx::int_t year, cx::int_t month, cx::int_t& day)

{

         cx::int_t month_days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

 

 

         if (gregorian_calendar_is_leap_year(year))

         {

                  month_days[1] = 29;

         }

 

        

         if ( !( 0<month && month<13) )

         {

                  return false;

         }

 

 

         day = month_days[month-1];

 

         return true;

}

 

cx::bool_t gregorian_calendar_is_valid_date (cx::int_t year, cx::int_t month, cx::int_t day)

{

         cx::int_t last_day_of_month;

 

 

 

         if (false==gregorian_calendar_get_last_day_of_month(year, month, last_day_of_month))

         {

                  return false;

         }

 

         if ( day < 0 || day > last_day_of_month )

         {

                  return false;

         }

 

         return true;

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

void epoch_to_jdn (cx::int_t base_epoch_jdn, cx::int_t day_number, cx::int_t& jdn)

{       

         jdn = base_epoch_jdn + day_number;

}

 

void epoch_to_date (cx::int_t base_epoch_jdn, cx::int_t day_number, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         cx::int_t jdn;

 

        

         epoch_to_jdn(base_epoch_jdn, day_number, jdn);

        

 

         jdn_to_gregorian_calendar_date(jdn, year, month, day);

}

 

void epoch_to_day_of_week (cx::int_t base_epoch_jdn, cx::int_t day_number, cx::int_t& day_of_week)

{

         cx::int_t jdn;

 

        

         epoch_to_jdn(base_epoch_jdn, day_number, jdn);

        

 

         day_of_week = us_get_day_of_week(jdn);

}

 

void epoch_to_time (cx::int_t daysecond_number, cx::int_t& hour, cx::int_t& minute, cx::int_t& second)

{

         hour   =  daysecond_number / 3600;

         minute = (daysecond_number % 3600) / 60;

         second = (daysecond_number % 3600) % 60;

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

cx::int_t epoch_second_get_day_number (cx::time_t epoch_second)

{

         const cx::int_t second_per_day = 86400; // 24*60*60;

        

         cx::int_t day_number;

 

 

         day_number = static_cast<cx::int_t>(epoch_second / second_per_day);

 

 

         return day_number;

}

 

cx::int_t epoch_second_get_daysecond_number (cx::time_t epoch_second)

{

         const cx::int_t second_per_day = 86400; // 24*60*60;

        

         cx::int_t daysecond_number;

 

 

         daysecond_number = static_cast<cx::int_t>(epoch_second % second_per_day);

 

 

         return daysecond_number;

}

 

//===========================================================================

void epoch_second_to_jdn (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& jdn)

{

         cx::int_t day_number;

 

        

         day_number = epoch_second_get_day_number(epoch_second);

        

 

         epoch_to_jdn(base_epoch_jdn, day_number, jdn);

}

 

void epoch_second_to_datetime (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& year, cx::int_t& month, cx::int_t& day, cx::int_t& day_of_week, cx::int_t& hour, cx::int_t& minute, cx::int_t& second)

{

         cx::int_t day_number;

         cx::int_t daysecond_number;

        

         cx::int_t jdn;

 

 

         day_number       = epoch_second_get_day_number      (epoch_second);

         daysecond_number = epoch_second_get_daysecond_number(epoch_second);

        

 

         epoch_to_jdn(base_epoch_jdn, day_number, jdn);

 

        

         jdn_to_gregorian_calendar_date(jdn, year, month, day);

         day_of_week = us_get_day_of_week(jdn);

 

        

         epoch_to_time(daysecond_number, hour, minute, second);

}

 

void epoch_second_to_date (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         cx::int_t day_number;

        

         cx::int_t jdn;

 

 

         day_number = epoch_second_get_day_number(epoch_second);

        

 

         epoch_to_jdn(base_epoch_jdn, day_number, jdn);

 

        

         jdn_to_gregorian_calendar_date(jdn, year, month, day);

}

 

void epoch_second_to_day_of_week (cx::int_t base_epoch_jdn, cx::time_t epoch_second, cx::int_t& day_of_week)

{

         cx::int_t day_number;

        

         cx::int_t jdn;

 

 

         day_number = epoch_second_get_day_number(epoch_second);

 

        

         epoch_to_jdn(base_epoch_jdn, day_number, jdn);

 

        

         day_of_week = us_get_day_of_week(jdn);

}

 

void epoch_second_to_time (cx::time_t epoch_second, cx::int_t& hour, cx::int_t& minute, cx::int_t& second)

{

         cx::int_t daysecond_number;

 

 

         daysecond_number = epoch_second_get_daysecond_number(epoch_second);

        

 

         epoch_to_time(daysecond_number, hour, minute, second);

}

 

void datetime_to_epoch_second (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t hour, cx::int_t minute, cx::int_t second, cx::int_t base_epoch_jdn, cx::time_t& epoch_second)

{

         const cx::int_t second_per_day = 86400; // 24*60*60;

 

         cx::int_t jdn;

 

         cx::time_t day_number;

         cx::time_t daysecond_number;

 

 

         gregorian_calendar_date_to_jdn (year, month, day, jdn);

 

        

         day_number       = jdn - base_epoch_jdn;

         daysecond_number = hour*3600 + minute*60 + second;

        

 

         epoch_second = day_number*second_per_day + daysecond_number;

}

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

cx::int_t unix_time_get_base_epoch_jdn (void)

{

         const cx::int_t base_jdn = 2440588; // 1970 01 01 12:00:00

 

 

         return base_jdn;

}

 

void unix_time_to_jdn (cx::time_t t, cx::int_t& jdn)

{

         epoch_second_to_jdn (unix_time_get_base_epoch_jdn(), t, jdn);

}

 

void unix_time_to_datetime (cx::time_t t, cx::int_t& year, cx::int_t& month, cx::int_t& day, cx::int_t& day_of_week, cx::int_t& hour, cx::int_t& minute, cx::int_t& second)

{

         epoch_second_to_datetime (unix_time_get_base_epoch_jdn(), t, year, month, day, day_of_week, hour, minute, second);

}

 

void unix_time_to_date (cx::time_t t, cx::int_t& year, cx::int_t& month, cx::int_t& day)

{

         epoch_second_to_date (unix_time_get_base_epoch_jdn(), t, year, month, day);

}

 

void unix_time_to_day_of_week (cx::time_t t, cx::int_t& day_of_week)

{

         epoch_second_to_day_of_week (unix_time_get_base_epoch_jdn(), t, day_of_week);

}

 

void unix_time_to_time (cx::time_t t, cx::int_t& hour, cx::int_t& minute, cx::int_t& second)

{

         epoch_second_to_time (t, hour, minute, second);

}

 

void datetime_to_unix_time (cx::int_t year, cx::int_t month, cx::int_t day, cx::int_t hour, cx::int_t minute, cx::int_t second, cx::time_t& t)

{

         datetime_to_epoch_second (year, month, day, hour, minute, second, unix_time_get_base_epoch_jdn(), t);

}


 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

void show (

         cx::int_t jdn        ,

         cx::int_t year       ,

         cx::int_t month      ,

         cx::int_t day        ,

         cx::int_t day_of_week,

         cx::int_t hour       ,

         cx::int_t minute     ,

         cx::int_t second

         )

{

         cx::int_t modified_jdn;

         cx::int_t truncated_jd;

         cx::int_t lilian_date;

         cx::int_t unix_time_day_count;

 

 

         jdn_to_modified_jdn       (jdn, modified_jdn       );

         jdn_to_truncated_jd       (jdn, truncated_jd       );

         jdn_to_lilian_date        (jdn, lilian_date        );

         jdn_to_unix_time_day_count(jdn, unix_time_day_count);

 

         printf ("%+05d-%02d-%02d(%d) %02d:%02d:%02d = %8d / MJDN=%8d, TJD=%8d, LILIAN=%8d, UNIX=%8d \r\n",

                  year,month,day, day_of_week,

                  hour, minute, second,

                  jdn,

                  modified_jdn       ,

                  truncated_jd       ,

                  lilian_date        ,

                  unix_time_day_count

                  );

}

 

int _tmain(int argc, _TCHAR* argv[])

{

         cx::int_t jdn         = 0;

         cx::int_t year        = 0;

         cx::int_t month       = 0;

         cx::int_t day         = 0;

         cx::int_t day_of_week = 0;

         cx::int_t hour        = 0;

         cx::int_t minute      = 0;

         cx::int_t second      = 0;

 

         cx::int_t day_count = 0;

 

         cx::time_t t;

 

 

         //-----------------------------------------------------------------------

         // 12h Jan 1, 4713 BC

         jdn = 0;

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         year  =-4712;

         month =1;

         day   =1;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

 

         //-----------------------------------------------------------------------

         // BC 1

         year  =0;

         month =1;

         day   =1;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

 

         //-----------------------------------------------------------------------

         // 1 AD

         year  =1;

         month =1;

         day   =1;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         // AD 2

         year  =2;

         month =1;

         day   =1;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         jdn = 2299161-2;

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         jdn = 2299161-1;

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         jdn = 2299161;

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         jdn = 2299161+1;

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

 

         year  =1582;

         month =10;

         day   = 3;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         year  =1582;

         month =10;

         day   = 4;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         // Lilian date : Oct 15, 1582 = floor (JD 2299159.5) ; Count of days of the Gregorian calendar

         year  =1582;

         month =10;

         day   =15;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         year  =1582;

         month =10;

         day   =16;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         // Reduced JD (JD - 2400000)

         year  =1858;

         month =11;

         day   =16;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         // Modified JD: 0h Nov 17, 1858 = (JD 2400000.5)

         year  =1858;

         month =11;

         day   =17;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         // Truncated JD: 0h May 24, 1968 = floor (JD 2440000.5) ; Introduced by NASA in 1979

         year  =1968;

         month =5;

         day   =24;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         // Unix Time: 0h Jan 1, 1970 = (JD 2440587.5) × 86400

         year  =1970;

         month =1;

         day   =1;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         year  =2000;

         month =1;

         day   =1;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

 

         //-----------------------------------------------------------------------

         year  =2018;

         month =10;

         day   =9;

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         printf ("\r\n");

 

 

         //-----------------------------------------------------------------------

         t = time(NULL) + 9*60*60;

 

         day_count = static_cast<cx::int_t>(t / 86400);

         printf ("time() / 86400 = %d \r\n", day_count);

 

         unix_time_to_jdn     (t, jdn);

         unix_time_to_datetime(t, year,month,day, day_of_week, hour, minute, second);

 

         show (jdn, year, month, day, day_of_week, hour, minute, second);

 

         calendar_date_to_jdn(year,month,day, jdn); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

         jdn_to_calendar_date(jdn, year,month,day); day_of_week = us_get_day_of_week(jdn); show(jdn, year, month, day, day_of_week, hour, minute, second);

 

         printf ("\r\n");

 

         return 0;

}

 

/*

-4712-01-01(1) 00:00:00 =        0 / MJDN=-2400001, TJD=-2440001, LILIAN=-2299160, UNIX=-2440588

-4712-01-01(1) 00:00:00 =        0 / MJDN=-2400001, TJD=-2440001, LILIAN=-2299160, UNIX=-2440588

 

+0000-01-01(4) 00:00:00 =  1721058 / MJDN= -678943, TJD= -718943, LILIAN= -578102, UNIX= -719530

+0000-01-01(4) 00:00:00 =  1721058 / MJDN= -678943, TJD= -718943, LILIAN= -578102, UNIX= -719530

 

+0001-01-01(6) 00:00:00 =  1721424 / MJDN= -678577, TJD= -718577, LILIAN= -577736, UNIX= -719164

+0001-01-01(6) 00:00:00 =  1721424 / MJDN= -678577, TJD= -718577, LILIAN= -577736, UNIX= -719164

 

+0002-01-01(0) 00:00:00 =  1721789 / MJDN= -678212, TJD= -718212, LILIAN= -577371, UNIX= -718799

+0002-01-01(0) 00:00:00 =  1721789 / MJDN= -678212, TJD= -718212, LILIAN= -577371, UNIX= -718799

 

+1582-10-03(3) 00:00:00 =  2299159 / MJDN= -100842, TJD= -140842, LILIAN=      -1, UNIX= -141429

+1582-10-04(4) 00:00:00 =  2299160 / MJDN= -100841, TJD= -140841, LILIAN=       0, UNIX= -141428

+1582-10-15(5) 00:00:00 =  2299161 / MJDN= -100840, TJD= -140840, LILIAN=       1, UNIX= -141427

+1582-10-16(6) 00:00:00 =  2299162 / MJDN= -100839, TJD= -140839, LILIAN=       2, UNIX= -141426

+1582-10-03(3) 00:00:00 =  2299159 / MJDN= -100842, TJD= -140842, LILIAN=      -1, UNIX= -141429

+1582-10-04(4) 00:00:00 =  2299160 / MJDN= -100841, TJD= -140841, LILIAN=       0, UNIX= -141428

+1582-10-15(5) 00:00:00 =  2299161 / MJDN= -100840, TJD= -140840, LILIAN=       1, UNIX= -141427

+1582-10-16(6) 00:00:00 =  2299162 / MJDN= -100839, TJD= -140839, LILIAN=       2, UNIX= -141426

 

+1858-11-16(2) 00:00:00 =  2400000 / MJDN=      -1, TJD=  -40001, LILIAN=  100840, UNIX=  -40588

+1858-11-16(2) 00:00:00 =  2400000 / MJDN=      -1, TJD=  -40001, LILIAN=  100840, UNIX=  -40588

 

+1858-11-17(3) 00:00:00 =  2400001 / MJDN=       0, TJD=  -40000, LILIAN=  100841, UNIX=  -40587

+1858-11-17(3) 00:00:00 =  2400001 / MJDN=       0, TJD=  -40000, LILIAN=  100841, UNIX=  -40587

 

+1968-05-24(5) 00:00:00 =  2440001 / MJDN=   40000, TJD=       0, LILIAN=  140841, UNIX=    -587

+1968-05-24(5) 00:00:00 =  2440001 / MJDN=   40000, TJD=       0, LILIAN=  140841, UNIX=    -587

 

+1970-01-01(4) 00:00:00 =  2440588 / MJDN=   40587, TJD=     587, LILIAN=  141428, UNIX=       0

+1970-01-01(4) 00:00:00 =  2440588 / MJDN=   40587, TJD=     587, LILIAN=  141428, UNIX=       0

 

+2000-01-01(6) 00:00:00 =  2451545 / MJDN=   51544, TJD=   11544, LILIAN=  152385, UNIX=   10957

+2000-01-01(6) 00:00:00 =  2451545 / MJDN=   51544, TJD=   11544, LILIAN=  152385, UNIX=   10957

 

+2018-10-09(2) 00:00:00 =  2458401 / MJDN=   58400, TJD=   18400, LILIAN=  159241, UNIX=   17813

+2018-10-09(2) 00:00:00 =  2458401 / MJDN=   58400, TJD=   18400, LILIAN=  159241, UNIX=   17813

 

time() / 86400 = 17809

+2018-10-05(5) 16:30:50 =  2458397 / MJDN=   58396, TJD=   18396, LILIAN=  159237, UNIX=   17809

+2018-10-05(5) 16:30:50 =  2458397 / MJDN=   58396, TJD=   18396, LILIAN=  159237, UNIX=   17809

+2018-10-05(5) 16:30:50 =  2458397 / MJDN=   58396, TJD=   18396, LILIAN=  159237, UNIX=   17809

 

*/

 


Posted by 셈말짓기 :

std::regx

2017. 8. 25. 09:09 from 셈말짓기/C and C++

#include "stdafx.h"

 

#include <regex>

#include <sstream>

#include <vector>

#include <iostream>

#include <vector>

 

void t4()

{

         //-----------------------------------------------------------------------

         std::string expression;

 

 

         //  ECMAScript : Special Keyword ^ $ \ . * + ? ( ) [ ] { } |

         expression = "\\\"([^\\\"]*)\\\"=([NR])";

         //       expression = R"STRING_LITERAL_DELIMITER(\"([^\"]*)\"=([NR]))STRING_LITERAL_DELIMITER";

         expression = R"d(\"([^\"]*)\"=([NR]))d";

         //       expression = R"d(\"([^\"]*)\")d";

 

 

         //-----------------------------------------------------------------------

         std::string text;

         std::string element;

 

         text = "  \"1A(:B/C)\":N, \"2AB,C\":R\"3A(:B/C)\":R, \"aa\"  ";

         text = "  \"21\"=N, \"22\"=R, \"23\"=R, \"24\"=x";

 

 

 

         //-----------------------------------------------------------------------

         std::vector<int> ei; // element index

 

 

         ei.push_back(1);

         ei.push_back(2);

         ei.push_back(3);

 

 

         //-----------------------------------------------------------------------

         std::regex                       r(expression);

         const std::sregex_token_iterator end;

         std::sregex_token_iterator       i(text.begin(), text.end(), r, ei);

 

 

         std::cout << expression << std::endl;

         std::cout << text << std::endl;

         while (i != end)

         {

                  element = *i++;

 

                  std::cout << element << std::endl;

         }

}

 

void t5()

{

         //-----------------------------------------------------------------------

         std::string expression;

 

 

         expression = R"d(\"([^\"]*)\"=([NR]))d";

 

 

         //-----------------------------------------------------------------------

         std::string text;

         std::string element;

 

 

         text = "  \"21\"=N, \"22\"=R, \"23\"=R, \"24\"=x";

 

 

         //-----------------------------------------------------------------------

         std::regex      r(expression);

         std::smatch     m;

         std::ssub_match sm;

 

         std::string value;

 

         std::size_t i;

         std::size_t count;

 

 

         value = text;

 

         while (std::regex_search(value, m, r))

         {

                  count = m.size();

 

                  for (i = 0u; i < count; i++)

                  {

                           sm = m[i];

 

                           if (sm.matched)

                           {

                                   element = sm.str();

 

                                   std::cout << i << " = " << element << std::endl;

                           }

                  }

 

                  value = m.suffix();

         }

}

 

int _tmain(int argc, _TCHAR* argv[])

{

         t5();

 

 

         return 0;

}

 

Posted by 셈말짓기 :


doxygen_template.zip


Posted by 셈말짓기 :

Image지원되는 RTF Editor입니다.


WTL기반으로 작성되었습니다.

COM 인터페이스로 이미지를 보여지게 하는 코드를 주서다가 만들었습니다.

그런데, RichEdit 8.0 부터는 이미지가 추가 API가 제공 됩니다. 








rtf_editor.zip





Posted by 셈말짓기 :

원격 디버깅으로 테스트 하다가

실행 못한다고 나오길레..

당연히 c-runtime dll들을 복사 해주면 될 줄 알았더니..

안되었음..

 

검색질 해보니

vs2008 sp1에서 manifest versions 가 업데이트 안되서

Microsoft.VC90.DebugCRT.manifest을 수정하면 된다고 함.

 

version="9.0.30729.4148"을 version="9.0.21022.8"으로 변경..

 

잘 됨.. -_-;

 

vs2008이 옛날꺼 되었어도 좀 고쳐라 MS..

 

http://stackoverflow.com/questions/3515450/installing-ms-debug-dlls-for-remote-debugging

 

참고..

- 원격 디버깅 서버 프로그램 경로

C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\msvsmon.exe

 

- DLL경로

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\redist

Posted by 셈말짓기 :

// Riff.cpp : 콘솔응용프로그램에대한진입점을정의합니다.

//

 

#include "stdafx.h"

#include <string.h>

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

typedef unsigned int       uint32_t;

typedef unsigned short int uint16_t;

typedef signed   short int int16_t;

typedef signed         int int32_t;

typedef unsigned char      byte_t;

 

inline uint32_t convert_endian_4byte (uint32_t v)

{

        return (((v>>24)&0xff)       )|

               (((v>>16)&0xff) << 8  )|

               (((v>> 8)&0xff) << 16 )|

               (((v    )&0xff) << 24 );

}

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

const uint32_t FOURCC_RIFF = 0x46464952; 

const uint32_t FOURCC_AVI  = 0x20495641; 

const uint32_t FOURCC_LIST = 0x5453494C; 

const uint32_t FOURCC_hdrl = 0x6C726468; 

const uint32_t FOURCC_avih = 0x68697661; 

const uint32_t FOURCC_strl = 0x6C727473; 

const uint32_t FOURCC_strh = 0x68727473; 

const uint32_t FOURCC_strf = 0x66727473; 

const uint32_t FOURCC_STRD = 0x64727473; 

const uint32_t FOURCC_vids = 0x73646976; 

const uint32_t FOURCC_auds = 0x73647561; 

const uint32_t FOURCC_INFO = 0x4F464E49; 

const uint32_t FOURCC_ISFT = 0x54465349; 

const uint32_t FOURCC_idx1 = 0x31786469; 

const uint32_t FOURCC_movi = 0x69766F6D; 

const uint32_t FOURCC_JUNK = 0x4B4E554A; 

const uint32_t FOURCC_vprp = 0x70727076; 

const uint32_t FOURCC_PAD  = 0x20444150; 

const uint32_t FOURCC_DIV3 = 861292868; 

const uint32_t FOURCC_DIVX = 1482049860; 

const uint32_t FOURCC_XVID = 1145656920; 

const uint32_t FOURCC_DX50 = 808802372; 

 

#define FOURCC(a,b,c,d) (((a)<<24)|((b)<<16)|((c)<<8)|(d))

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

typedef struct _riff_header_t

{

        uint32_t riff ;

        uint32_t size ;

        uint32_t type ;

} riff_header_t;

 

typedef struct _list_header_t

{

        uint32_t list   ;

        uint32_t size   ;

        uint32_t fourcc ;

} list_header_t;

 

typedef struct _chunk_header_t

{

        uint32_t fourcc ;

        uint32_t size   ;

} chunk_header_t;

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

typedef struct _MainAVIHeader_t

{

        uint32_t MicroSecPerFrame;   // frame display rate (or 0)

        uint32_t MaxBytesPerSec;     // max. transfer rate

        uint32_t PaddingGranularity; // pad to multiples of this size;

        uint32_t Flags;              // the ever-present flags

        uint32_t TotalFrames;        // # frames in file

        uint32_t InitialFrames;

        uint32_t Streams;

        uint32_t SuggestedBufferSize;

        uint32_t Width;

        uint32_t Height;

        uint32_t Reserved[4];

} MainAVIHeader_t;

 

typedef struct _RECT_t

{ 

    int16_t left; 

    int16_t top;  

    int16_t right;

    int16_t bottom;

} RECT_t; 

 

typedef struct _AVIStreamHeader_t

{             

    uint32_t fccType;

    uint32_t fccHandler;        

    uint32_t Flags;             

    uint16_t Priority;          

    uint16_t Language;          

    uint32_t InitialFrames;     

    uint32_t Scale;             

    uint32_t Rate;              

    uint32_t Start;             

    uint32_t Length;            

    uint32_t SuggestedBufferSize;

    uint32_t Quality;           

    uint32_t SampleSize;        

    RECT_t   FrameRect;         

} AVIStreamHeader_t; 

 

// strl - strh==vids  strf

typedef struct _BitmapInfoHeader_t

{ 

    uint32_t  biSize; 

    int32_t   biWidth; 

    int32_t   biHeight; 

    uint16_t  biPlanes; 

    uint16_t  biBitCount; 

    uint32_t  biCompression; 

    uint32_t  biSizeImage; 

    int32_t   biXPelsPerMeter; 

    int32_t   biYPelsPerMeter; 

    uint32_t  biClrUsed; 

    uint32_t  biClrImportant; 

} BitmapInfoHeader_t; 

 

// strl - strh==auds  strf

typedef struct _WaveFormatEx_t

{ 

    uint16_t FormatTag; 

    uint16_t Channels;        

    uint32_t SamplesPerSec;  

    uint32_t AvgBytesPerSec; 

    uint16_t BlockAlign;      

    uint16_t BitsPerSample;   

    uint16_t Size;           

} WaveFormatEx_t;

 

// AVI

typedef struct _avi_info_t

{

        uint32_t HasVideo;

        uint32_t HasAudio;

 

        uint32_t avi_size;

        uint32_t movi_size;

       

        uint32_t audio_data_size;

        uint32_t audio_data_count;

        uint32_t video_data_size;

        uint32_t video_data_count;

 

        MainAVIHeader_t    Header;

        AVIStreamHeader_t  Video;             // strh

        BitmapInfoHeader_t VideoBitmapInfo;   // strf

        AVIStreamHeader_t  Audio;             // strh

        WaveFormatEx_t     AudioWaveFormatEx; // strf

} avi_info_t;

 

bool read_avi_header (const char* filepath, avi_info_t* ai)

{

        FILE* fp;

 

        fp = fopen (filepath, "rb");

        if (0==fp)

        {

               return false;

        }

 

        //--------------------------------------------------------------------------

        // RIFF header

        //--------------------------------------------------------------------------

        riff_header_t riff_header;

 

        // [RIFF] size [AVI ]

        fread(&riff_header, sizeof(riff_header), 1, fp);

        printf ("%c%c%c%c %d %c%c%c%c \r\n",

               (riff_header.riff>> 0)&0xff,

               (riff_header.riff>> 8)&0xff,

               (riff_header.riff>>16)&0xff,

               (riff_header.riff>>24)&0xff,

                riff_header.size ,

               (riff_header.type>> 0)&0xff,

               (riff_header.type>> 8)&0xff,

               (riff_header.type>>16)&0xff,

               (riff_header.type>>24)&0xff

                );

 

        if (riff_header.riff != 0x46464952) // "RIFF"

        {

               fclose (fp);

               return false;

        }

 

        if (riff_header.type != 0x20495641) // "AVI "

        {

               fclose (fp);

               return false;

        }

        ai->avi_size = riff_header.size;

 

        //--------------------------------------------------------------------------

        // RIFF body

        //--------------------------------------------------------------------------

        int32_t  seek_size;

 

        uint32_t id;

        int32_t  size;

        uint32_t fourcc;

 

        uint32_t data_size;

 

        MainAVIHeader_t    MainAVIHeader;

        AVIStreamHeader_t  AVIStreamHeader;

        BitmapInfoHeader_t BitmapInfoHeader;

        WaveFormatEx_t     WaveFormatEx;

        uint32_t           strh = 0;

 

        while ( !feof(fp) )

        {

               printf ("%8d: ", ftell (fp));

 

               if (0==fread(&id, 4, 1, fp))

               {

                       break;

               }

               if (0==fread(&size,4, 1, fp))

               {

                       break;

               }

               printf ("<%c%c%c%c> %d \r\n",

                       (id>> 0)&0xff,

                       (id>> 8)&0xff,

                       (id>>16)&0xff,

                       (id>>24)&0xff,

                       size        );

               if (0==id)

               {

                       break;

               }

               if (0>=size)

               {

                       break;

               }

 

               // "LIST"

               if (id==0x5453494c)

               {

                       if (0==fread(&fourcc,  4, 1, fp))

                       {

                              break;

                       }

 

                       printf ("          %c%c%c%c\r\n",

                              (fourcc>> 0)&0xff,

                              (fourcc>> 8)&0xff,

                              (fourcc>>16)&0xff,

                              (fourcc>>24)&0xff);

 

                       if (fourcc == 0x69766F6D)

                       {

                              ai->movi_size = size;

                       }

               }

               else

               {

                       seek_size = (int32_t) size;

                       data_size = (int32_t) size;

 

                       // "avih"

                       if (id==0x68697661)

                       {

                              data_size = sizeof(MainAVIHeader);

                              if (0==fread (&MainAVIHeader, data_size, 1, fp))

                              {

                                      break;

                              }

                              memcpy (&ai->Header, &MainAVIHeader, data_size);

                             

                              seek_size = ( size!=data_size ) ?  size-data_size : 0;

                       }

 

                       // "strh"

                       if (id==0x68727473)

                       {

                              data_size = sizeof(AVIStreamHeader);

                              if (0==fread (&AVIStreamHeader, data_size, 1, fp))

                              {

                                      break;

                              }

 

                              printf ("          %c%c%c%c:%c%c%c%c\r\n",

                                      (AVIStreamHeader.fccType   >> 0)&0xff,

                                      (AVIStreamHeader.fccType   >> 8)&0xff,

                                      (AVIStreamHeader.fccType   >>16)&0xff,

                                      (AVIStreamHeader.fccType   >>24)&0xff,

                                      (AVIStreamHeader.fccHandler>> 0)&0xff,

                                      (AVIStreamHeader.fccHandler>> 8)&0xff,

                                      (AVIStreamHeader.fccHandler>>16)&0xff,

                                      (AVIStreamHeader.fccHandler>>24)&0xff);

 

                              strh = 0;

                              // "vids"

                              if (0x73646976==AVIStreamHeader.fccType)

                              {

                                      strh = 1;

                                      memcpy(&ai->Video, &AVIStreamHeader, data_size);

                                      ai->HasVideo = 1;

                              }

                              // "auds"

                              if (0x73647561==AVIStreamHeader.fccType)

                              {

                                      strh = 2;

                                      memcpy(&ai->Audio, &AVIStreamHeader, data_size);

                                      ai->HasAudio = 1;

                              }

 

                              seek_size = ( size!=data_size ) ?  size-data_size : 0;

                       }

 

                       // "strf"

                       if (id==0x66727473)

                       {

                              data_size = 0;

 

                              if (1==strh)

                              {

                                      data_size = sizeof(BitmapInfoHeader);

                                      if (0==fread (&BitmapInfoHeader, data_size, 1, fp))

                                      {

                                             break;

                                      }

                                      memcpy(&ai->VideoBitmapInfo, &BitmapInfoHeader, data_size);

                              }

                              if (2==strh)

                              {

                                      data_size = sizeof(WaveFormatEx);

                                      if (0==fread (&WaveFormatEx, data_size, 1, fp))

                                      {

                                             break;

                                      }

                                      memcpy(&ai->AudioWaveFormatEx, &WaveFormatEx, data_size);

                              }

 

                              seek_size = ( size!=data_size ) ?  size-data_size : 0;

                       }

 

                       // "00dc" : Compressed video frame

                       if ((id&0xffff0000)==0x63640000)

                       {

                              ai->video_data_size += size;

                              ai->video_data_count++;

                       }

                       // "00db" : Uncompressed video frame

                       if ((id&0xffff0000)==0x62640000)

                       {

                              ai->video_data_size += size;

                              ai->video_data_count++;

                       }

                       // "00pc" : Palette change

                       if ((id&0xffff0000)==0x63700000)

                       {

                              ai->video_data_size += size;

                              ai->video_data_count++;

                       }

                       // "00wb" : Audio data

                       if ((id&0xffff0000)==0x62770000)

                       {

                              ai->audio_data_size += size;

                              ai->audio_data_count++;

                       }

 

                       //

                       if ( 0!=seek_size )

                       {

                              if ( data_size != size )

                              {

                                      printf ("          # data_size(%d) != size(%d)\r\n", data_size, size);

                              }

                              if (0!=(seek_size%2))

                              {

                                      seek_size+=(seek_size%2);

                              }

                              if (-1==fseek (fp, seek_size, SEEK_CUR))

                              {

                                      break;

                              }

                       }

               }

        }

 

        fclose (fp);

 

        return true;

}

 

int _tmain(int argc, _TCHAR* argv[])

{

        avi_info_t avi;

 

        memset (&avi,0,sizeof(avi));

 

        if (true==read_avi_header ("d:\\test.avi", &avi))

        {

               printf ("\r\n");

               printf ("OK\r\n");

 

               double fps;

               double duration;

              

               double VideoFramesPerSec;

               double AudioBlockPerSec ;

 

               int HeaderSize;

               int VideoSize ;

               int AudioSize ;

 

               double VideoBitRate;

               double AudioBitRate;

               double FileBitRate;

 

               fps      = 1000000.0f/(double)avi.Header.MicroSecPerFrame;

               duration = avi.Header.TotalFrames / fps;

 

               AudioBlockPerSec  = (double)avi.Audio.Rate / (double)avi.Audio.Scale;

               VideoFramesPerSec = (double)avi.Video.Rate / (double)avi.Video.Scale;

              

               /*

               HeaderSize = avi.Header.TotalFrames * 8 * (avi.audio_data_count + 1);

               AudioSize  = (int)((avi.Audio.Length * avi.AudioWaveFormatEx.AvgBytesPerSec)/AudioBlockPerSec) * avi.audio_data_count;

               VideoSize  = avi.movi_size - HeaderSize - AudioSize;

               */

               HeaderSize = avi.movi_size - avi.video_data_size - avi.audio_data_size;

               AudioSize  = avi.audio_data_size;

               VideoSize  = avi.video_data_size;

 

               FileBitRate  = avi.avi_size * 8.0 / duration / 1000.0;

               AudioBitRate = avi.AudioWaveFormatEx.AvgBytesPerSec*8.0/1000.0;

               VideoBitRate = FileBitRate - AudioBitRate; // Windows AVI File Property

               VideoBitRate = (VideoSize * VideoFramesPerSec * 8.0)/(avi.Header.TotalFrames*1000.0);

 

               printf ("\r\n");

 

                if (avi.HasVideo)

               {

                       printf ("[비디오] \r\n");

                       printf ("길이          = %5.3f \r\n", duration);

                       printf ("프레임너비   = %d\r\n", avi.Header.Width);

                       printf ("프레임높이   = %d\r\n", avi.Header.Height);

                       printf ("데이터속도   = %5.3f kbps \r\n", VideoBitRate);                    

                       printf ("총비트전송률= %5.3f kbps\r\n", FileBitRate);

                       printf ("프레임속도   = %5.3f 프레임/\r\n", fps);

 

                       printf ("\r\n");

               }

 

               if (avi.HasAudio)

               {

                       printf ("[오디오] \r\n");

                       printf ("비트전송율      = %5.3f kbps \r\n", AudioBitRate);

                       printf ("채널            = %d \r\n", avi.AudioWaveFormatEx.Channels);

                       printf ("오디오샘플속도= %5.3f KHz\r\n", AudioBlockPerSec / 1000);

 

                       printf ("\r\n");

               }

        }

 

        return 0;

}

 

/*

 

RIFF 2317980 AVI

      12: <LIST> 8818

          hdrl

      24: <avih> 56

      88: <LIST> 4244

          strl

     100: <strh> 56

          vids:

     164: <strf> 40

     212: <JUNK> 4120

    4340: <LIST> 4222

          strl

    4352: <strh> 56

          auds:

    4416: <strf> 18

          # data_size(20) != size(18)

    4442: <JUNK> 4120

    8570: <LIST> 260

          odml

    8582: <dmlh> 248

    8838: <LIST> 28

          INFO

    8850: <ISFT> 15

    8874: <JUNK> 1358

   10240: <LIST> 2281204

          movi

   10252: <01wb> 24000

   34260: <00dc> 22306

   56574: <01wb> 1920

   58502: <00dc> 159

   58670: <01wb> 1920

...

 2290948: <00dc> 159

 2291116: <00dc> 159

 2291284: <00dc> 159

 2291452: <idx1> 26528

 2317988: <JUNK> 340

 2318336:

OK

 

[비디오]

길이          = 33.400

프레임너비   = 640

프레임높이   = 480

데이터속도   = 159.297 kbps

총비트전송률= 555.205 kbps

프레임속도   = 25.000 프레임/

 

[오디오]

비트전송율      = 384.000 kbps

채널            = 5

오디오샘플속도= 48.000 KHz

 

*/

Posted by 셈말짓기 :

#. ReBar 컨트롤에 집어 넣을 윈도우 구현

   - TB_BUTTONCOUNT, TB_GETITEMRECT 2개의 메세지 구현해주면 ReBar에 넣을수있다.

 

 


/////////////////////////////////////////////////////////////////////////////
class C_WTLWINVIEW_View : public CWindowImpl<C_WTLWINVIEW_View>
{
public:
 DECLARE_WND_CLASS(NULL)

 BOOL PreTranslateMessage(MSG* pMsg)
 {
  pMsg;
  return FALSE;
 }

 BEGIN_MSG_MAP(C_WTLWINVIEW_View)
  MESSAGE_HANDLER ( WM_PAINT            , OnPaint              )
  MESSAGE_HANDLER ( TB_BUTTONCOUNT      , OnTB_ButtonCount     )
  MESSAGE_HANDLER ( TB_GETITEMRECT      , OnTB_GetItemRect     )
  MESSAGE_HANDLER ( TB_GETEXTENDEDSTYLE , OnTB_GetExtendedStyle)
  MESSAGE_HANDLER ( TB_SETEXTENDEDSTYLE , OnTB_SetExtendedStyle)
 END_MSG_MAP()

 // Handler prototypes (uncomment arguments if needed):
 // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
 // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)

 LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 {
  CPaintDC dc(m_hWnd);

  //TODO: Add your drawing code here

  return 0;
 }
 LRESULT OnTB_ButtonCount(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 {
  // return int item count
  // wParam int 0
  // lParam int 0
  return 1;
 }
 LRESULT OnTB_GetItemRect(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
 {
  // return BOOL  success
  // wParam int   button index
  // lParam RECT* button rect

  LPRECT lpRect = (LPRECT)lParam;

  lpRect->left  =0;
  lpRect->top   =0;
  lpRect->right =100;
  lpRect->bottom=20;

  return 1;
 }
 LRESULT OnTB_GetExtendedStyle(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 {
  // return DWORD style
  // wParam int   0
  // lParam int   0
  return 0;
 }
 LRESULT OnTB_SetExtendedStyle(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 {
  // return DWORD style
  // wParam int   0
  // lParam int   new style
  return 0;
 }
};

WTL::CFrameWindowImplBase::AddSimpleReBarBandCtrl()

 

/////////////////////////////////////////////////////////////////////////////

//

// Class: CMyToolWindow

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

class CMyToolWindow : public CWindowImpl<CMyToolWindow>

{

public:

        //DECLARE_WND_CLASS(NULL)

        DECLARE_WND_CLASS_EX (NULL, CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS, (HBRUSH)(COLOR_APPWORKSPACE))

 

        BOOL PreTranslateMessage(MSG* pMsg)

        {

               pMsg;

               return FALSE;

        }

 

        BEGIN_MSG_MAP(CMyToolWindow)

               MESSAGE_HANDLER(TB_BUTTONCOUNT, OnToolBarButtonCount)

               MESSAGE_HANDLER(TB_GETITEMRECT, OnToolBarItemRect   )

               MESSAGE_HANDLER(WM_PAINT, OnPaint)

        END_MSG_MAP()

 

        LRESULT OnToolBarButtonCount(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)

        {

               return 1;

        }

 

        LRESULT OnToolBarItemRect   (UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)

        {

               int    nButtonCount = (int)   wParam;

               LPRECT pRect        = (LPRECT)lParam;

 

               pRect->left   =0;

               pRect->top    =0;

 

               if (nButtonCount>0)

                       pRect->right  =100*nButtonCount;

               else

                       pRect->right  =100;

               pRect->bottom =25;

 

               return 1;

        }

 

        LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)

        {

               CPaintDC dc(m_hWnd);

 

               //TODO: Add your drawing code here

               dc.TextOut (0,0,_T("xxx"));

               return 0;

        }

};

 

 

 

#. MainFrame 윈도우에서

 

CMyToolWindow m_MyToolWindow;

 

LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)

{

        HWND hWndCmdBar;

        HWND hWndToolBar;

 

        hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE);

        m_CmdBar.AttachMenu(GetMenu());

        m_CmdBar.LoadImages(IDR_MAINFRAME);

        SetMenu(NULL);

 

        hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE);

 

        m_MyToolWindow.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_STATICEDGE);

 

        // Rebar

        CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE);

        AddSimpleReBarBand(hWndCmdBar);

        AddSimpleReBarBand(hWndToolBar, NULL, TRUE);

        AddSimpleReBarBand(m_MyToolWindow, _T("MyToolWindow"), TRUE, 100, TRUE);

 

        // StatusBar

        CreateSimpleStatusBar();

 

        // View

        m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);

 

        UIAddToolBar(hWndToolBar);

        UISetCheck(ID_VIEW_TOOLBAR, 1);

        UISetCheck(ID_VIEW_STATUS_BAR, 1);

 

        // register object for message filtering and idle updates

        CMessageLoop* pLoop = _Module.GetMessageLoop();

        ATLASSERT(pLoop != NULL);

        pLoop->AddMessageFilter(this);

        pLoop->AddIdleHandler(this);

 

        return 0;

}

 

Posted by 셈말짓기 :

TCHAR      text[128];

SYSTEMTIME st;

int        result = 0;

 

GetLocalTime (&st);

 

result = GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, text, 128);

if (result)

{

        // printf (text);

}

 

result = GetTimeFormat(LOCALE_USER_DEFAULT, /*LOCALE_NOUSEROVERRIDE*/0, &st, _T("HH:mm:ss"), text, 128);

if (result)

{

        // printf (text);

}

 

Posted by 셈말짓기 :

# link 기본
#     g++ -o hellox -Wall -D_REENTRANT         \
#         /usr/lib/i386-linux-gnu/libpthread.a \
#         /usr/X11R6/lib/libX11.so             \
#         ./libprint.so                        \
#         ./hellox.o                          
# g++
#     -l라이브러리파일명중lib제외한부분[libXXXX.a]
#         [예] -lpthread -> libpthread.a
#     -L라이브러리파일libXXXX.a찾을경로
#         [예] $(CXX) -o hellox -Wall -D_REENTRANT -lpthread /usr/X11R6/lib/libX11.so hellox.o
#              $(CXX) -o hellox -Wall -D_REENTRANT -lpthread -lX11 hellox.o -L/usr/X11R6/lib
#     -Wl,ld명령파라메터
#         ld명령에 파라메터 전송 구분자, 구분자,는 공백문자로 변경됨
#         -Wl,이후 공백문자를 사용하지말것

LIB_PTHREAD     = /usr/lib/i386-linux-gnu/libpthread.a

INC_X11_DESKTOP = /usr/X11R6/include
LIB_X11_DESKTOP = /usr/X11R6/lib/libX11.so
LIB_X11_DEUTA   = /opt/mft1-gcc/target/extended/xlib6g/usr/X11R6/lib/libX11.so.6

ifeq '$(MAKECMDGOALS)' ''
prepared_error:
 @echo "No target!"
endif

ifeq '$(MAKECMDGOALS)' 'all'
INC_X11 = $(INC_X11_DESKTOP)
LIB_X11 = $(LIB_X11_DESKTOP)
endif

compile:
 @echo ""
 @echo "============================================================================="
 @echo "compile"
 @echo "============================================================================="
 $(CXX) -o hellox.o    -ansi -pedantic -Wall -I$(INC_X11) -c  hellox.c
 $(CXX) -o libprint.so -ansi -pedantic -Wall -fPIC -shared    libprint.c -Wl,-Map,libprint.map

link:
 @echo ""
 @echo "============================================================================="
 @echo "link"
 @echo "============================================================================="
 $(CXX) -o hellox      -Wall -D_REENTRANT $(LIB_PTHREAD) $(LIB_X11) libprint.so hellox.o -Wl,--rpath,.,-Map,hellox.map

clean:
 @echo ""
 @echo "============================================================================="
 @echo "clean"
 @echo "============================================================================="
 rm -f *.o
 rm -f *.so
 rm -f *.map
 rm -f hellox
 
all: clean compile link

execute:
 @echo ""
 @echo "============================================================================="
 @echo "execute"
 @echo "============================================================================="
 ./hellox

show_make:
 @echo ""
 @echo "============================================================================="
 @echo "show make variables"
 @echo "============================================================================="
 @echo "MAKEFILES    = $(MAKEFILES)"
 @echo "VPATH        = $(VPATH)"
 @echo "SHELL        = $(SHELL)"
 @echo "MAKESHELL    = $(MAKESHELL)"
 @echo "MAKE         = $(MAKE)"
 @echo "MAKELEVEL    = $(MAKELEVEL)"
 @echo "MAKEFLAGS    = $(MAKEFLAGS)"
 @echo "MAKECMDGOALS = $(MAKECMDGOALS)"
 @echo "CURDIR       = $(CURDIR)"
 @echo "SUFFIXES     = $(SUFFIXES)"

show_rpath:
 @echo ""
 @echo "============================================================================="
 @echo "show rpath"
 @echo "============================================================================="
 objdump -x hellox |grep RPATH
# readelf -d hellox |head -20

Posted by 셈말짓기 :


/////////////////////////////////////////////////////////////////////////////

//

// File: FSMSample.cpp

//

// Created by MOON, Eui-kwon.

// Created on Aug-10th, 2011.

//

// 교육용으로작성한FSM Sample.

// 예전에FSM 공부할때cdplayer라는샘플코드를본것같은데코드는없고

// 웹에상태천이표만있어서그기준으로코드를작성함.

//

// machine, state, event 각각의인터페이스는비지터패턴형식으로구성함.

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

 

 

 

#include "stdafx.h"

#include <assert.h>

 

/////////////////////////////////////////////////////////////////////////////

//

// Finite state machine

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

namespace fsm

{

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

class event;

class state;

class machine;

 

 

 

/////////////////////////////////////////////////////////////////////////////

//

// Interface

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

class machine

{

private:

        state* _state;

       

public:

        machine();

        virtual ~machine();

 

public:

        virtual void   transition (state*);

        virtual void   notify     (event*);

        virtual state* get_state  (void  ) const;

};

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

class event

{

public:

        event();

        virtual ~event();

 

public:

        virtual void notify (machine*, state*);

};

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

class state

{

public:

        state();

        virtual ~state();

       

public:

        virtual void on_entry   (machine*, state*);

        virtual void on_exit    (machine*, state*);

        virtual void on_event   (machine*, event*);

 

public:

        virtual void transition (machine*, state*);

};

 

 

 

 

/////////////////////////////////////////////////////////////////////////////

//

// Implementation

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

event:: event(){}

event::~event(){}

 

void event::notify (machine* m, state*s)

{

        if (s)

        {

               s->on_event (m, this);

        }

}

 

//===========================================================================

state:: state(){}

state::~state(){}

 

void state::on_entry (machine*, state*) {}

void state::on_exit  (machine*, state*) {}

void state::on_event (machine*, event*) {}

 

void state::transition (machine* m, state* s)

{

        if (m)

        {

               m->transition (s);

        }

}

 

//===========================================================================

machine::machine():

        _state (0)

{

}

 

machine::~machine()

{

}

 

state* machine::get_state (void) const

{

        return _state;

}

 

void machine::transition (state* current)

{      

        state* previous;

 

        previous = _state;

        if (previous)

        {

               previous->on_exit (this, current );

        }

 

        _state = current;

        if (current)

        {

               current ->on_entry (this, previous);

        }

}

 

void machine::notify (event* e)

{

        if (e)

        {

               e->notify (this, _state);

        }

}

 

}; // end of "namespace fsm"

 

 

 

/////////////////////////////////////////////////////////////////////////////

//

// Sample

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

#define fsm_trace  printf

#define fsm_assert assert

 

//===========================================================================

enum cdplayer_event_code_t

{

        ec_play        = 0,

        ec_open_close  = 1,

        ec_cd_detected = 2,

        ec_stop        = 3,

        ec_pause       = 4

};

 

//===========================================================================

class cdplayer_event : public fsm::event

{

public:

        const cdplayer_event_code_t _code;

 

        explicit cdplayer_event (cdplayer_event_code_t code) : _code(code)

        {

        }

 

        void notify (fsm::machine* m, fsm::state*s)

        {

               switch (_code)

               {

               case ec_play       : fsm_trace("\t\tnotify: play        \r\n"); break;

               case ec_open_close : fsm_trace("\t\tnotify: open_close  \r\n"); break;

               case ec_cd_detected: fsm_trace("\t\tnotify: cd_detected \r\n"); break;

               case ec_stop       : fsm_trace("\t\tnotify: stop        \r\n"); break;

               case ec_pause      : fsm_trace("\t\tnotify: pause       \r\n"); break;

               }

 

               fsm::event::notify (m, s);

        }

};

 

//===========================================================================

class cdplayer_state : public fsm::state

{

public:

        virtual const char* get_name (void) = 0;

 

        virtual void on_event (fsm::machine* m, fsm::event* e)

        {

               /*

               cdplayer*       cm = static_cast<cdplayer*      > ( m );

               cdplayer_event* ce = static_cast<cdplayer_event*> ( e );

 

               switch (ce->_code)

               {

               case ec_play       : break;

               case ec_open_close : break;

               case ec_cd_detected: break;

               case ec_stop       : break;

               case ec_pause      : break;

               }

               */

        }

 

        virtual void on_entry (fsm::machine*, fsm::state*)

        {

               fsm_trace("\ton_entry: %s \r\n", get_name());

        }

 

        virtual void on_exit (fsm::machine*, fsm::state*)

        {

               fsm_trace("\ton_exit : %s \r\n", get_name());

        }

};

#define DECLARE_NAME(n) virtual const char* get_name (void) { return (n); }

 

//===========================================================================

class stopped: public cdplayer_state

{

public:

        DECLARE_NAME ("stopped" )

        virtual void on_event (fsm::machine* m, fsm::event* e);

};

 

//===========================================================================

class open: public cdplayer_state

{

public:

        DECLARE_NAME ("open" )

        virtual void on_event (fsm::machine* m, fsm::event* e);

};

 

//===========================================================================

class empty: public cdplayer_state

{

public:

        DECLARE_NAME ("empty" )

        virtual void on_event (fsm::machine* m, fsm::event* e);

};

 

//===========================================================================

class playing: public cdplayer_state

{

public:

        DECLARE_NAME ("playing" )

        virtual void on_event (fsm::machine* m, fsm::event* e);

};

 

//===========================================================================

class paused: public cdplayer_state

{

public:

        DECLARE_NAME ("paused" )

        virtual void on_event (fsm::machine* m, fsm::event* e);

};

 

//===========================================================================

class cdplayer: public fsm::machine

{

private:

        stopped _stopped;

        open    _open   ;

        empty   _empty  ;

        playing _playing;

        paused  _paused ;

 

public:

        enum state_id_t

        {

               sid_stopped,

               sid_open   ,

               sid_empty  ,

               sid_playing,

               sid_paused ,

        };

 

public:

        virtual void transition (fsm::state* n)

        {

               cdplayer_state* previous = static_cast<cdplayer_state*> ( get_state() );

               cdplayer_state* current  = static_cast<cdplayer_state*> ( n );

 

               fsm_trace ("transition:");

               if (previous) fsm_trace (" %s -> ", previous->get_name());

               if (current ) fsm_trace (" %s ", current ->get_name());

               fsm_trace ("\r\n");

 

               fsm::machine::transition(n);

        }

 

        cdplayer_state* get_state_instance (state_id_t id)

        {

               switch (id)

               {

               case sid_stopped : return &_stopped ;

               case sid_open    : return &_open    ;

               case sid_empty   : return &_empty   ;

               case sid_playing : return &_playing ;

               case sid_paused  : return &_paused  ;

               }

 

               fsm_assert (0);

 

               return 0;

        }

 

public:

        void start_playback         (void){ printf("\t\t\taction: start_playback         \r\n"); }

        void open_drawer            (void){ printf("\t\t\taction: open_drawer            \r\n"); }

        void close_drawer           (void){ printf("\t\t\taction: close_drawer           \r\n"); }

        void collect_cd_information (void){ printf("\t\t\taction: collect_cd_information \r\n"); }

        void store_cd_information   (void){ printf("\t\t\taction: store_cd_information   \r\n"); }

        void stop_playback          (void){ printf("\t\t\taction: stop_playback          \r\n"); }

        void pause_playback         (void){ printf("\t\t\taction: pause_playback         \r\n"); }

        void resume_playback        (void){ printf("\t\t\taction: resume_playback        \r\n"); }

};

 

/*********************************************************************************

 CD PLAYER STATE TRANSITION TABLE

---------------+-------------+------------+--------------------------------------

 CURRENT STATE | EVENT       | NEXT STATE | TRANSITION ACTION

---------------+-------------+------------+--------------------------------------

 stopped       | play        | playing    | start playback

 stopped       | open/close  | open       | open drawer

 open          | open/close  | empty      | close drawer; collect cd information

 empty         | open/close  | open       | open drawer

 empty         | cd-detected | stopped    | store cd information

 playing       | stop        | stopped    | stop playback

 playing       | pause       | paused     | pause playback

 playing       | open/close  | open       | stop playback; open drawer

 paused        | play        | playing    | resume playback

 paused        | stop        | stopped    | stop playback

 paused        | open/close  | open       | stop playback; open drawer

---------------+-------------+------------+--------------------------------------

*********************************************************************************/

 

//===========================================================================

void stopped::on_event (fsm::machine* m, fsm::event* e)

{

        cdplayer*       cm = static_cast<cdplayer*      > ( m );

        cdplayer_event* ce = static_cast<cdplayer_event*> ( e );

 

        switch (ce->_code)

        {

        case ec_play :

               cm->start_playback();

               transition(cm, cm->get_state_instance (cdplayer::sid_playing));

               break;

 

        case ec_open_close :

               cm->open_drawer ();

               transition(cm, cm->get_state_instance (cdplayer::sid_open));

               break;

        }

}

 

//===========================================================================

void open::on_event (fsm::machine* m, fsm::event* e)

{

        cdplayer*       cm = static_cast<cdplayer*      > ( m );

        cdplayer_event* ce = static_cast<cdplayer_event*> ( e );

 

        switch (ce->_code)

        {

        case ec_open_close :

               cm->close_drawer();

               cm->collect_cd_information();

               transition(cm, cm->get_state_instance (cdplayer::sid_empty));

               break;

        }

}

 

//===========================================================================

void empty::on_event (fsm::machine* m, fsm::event* e)

{

        cdplayer*       cm = static_cast<cdplayer*      > ( m );

        cdplayer_event* ce = static_cast<cdplayer_event*> ( e );

 

        switch (ce->_code)

        {

        case ec_open_close :

               cm->open_drawer();

               transition(cm, cm->get_state_instance (cdplayer::sid_open));

               break;

 

        case ec_cd_detected:

               cm->store_cd_information();

               transition(cm, cm->get_state_instance (cdplayer::sid_stopped));

               break;

        }

}

 

//===========================================================================

void playing::on_event (fsm::machine* m, fsm::event* e)

{

        cdplayer*       cm = static_cast<cdplayer*      > ( m );

        cdplayer_event* ce = static_cast<cdplayer_event*> ( e );

 

        switch (ce->_code)

        {

        case ec_stop :

               cm->stop_playback();

               transition(cm, cm->get_state_instance (cdplayer::sid_stopped));

               break;

 

        case ec_pause :

               cm->pause_playback();

               transition(cm, cm->get_state_instance (cdplayer::sid_paused));

               break;

 

        case ec_open_close :

               cm->stop_playback();

               cm->open_drawer();

               transition(cm, cm->get_state_instance (cdplayer::sid_open));

               break;

        }

}

//===========================================================================

void paused::on_event (fsm::machine* m, fsm::event* e)

{

        cdplayer*       cm = static_cast<cdplayer*      > ( m );

        cdplayer_event* ce = static_cast<cdplayer_event*> ( e );

 

        switch (ce->_code)

        {

        case ec_play :

               cm->resume_playback();

               transition(cm, cm->get_state_instance (cdplayer::sid_playing));

               break;

 

        case ec_stop :

               cm->stop_playback();

               transition(cm, cm->get_state_instance (cdplayer::sid_stopped));

               break;

 

        case ec_open_close :

               cm->stop_playback();

               cm->open_drawer();

               transition(cm, cm->get_state_instance (cdplayer::sid_open));

               break;

        }

}

//===========================================================================

int _tmain(int argc, _TCHAR* argv[])

{

        cdplayer       player;

        cdplayer_event play        (ec_play       );

        cdplayer_event open_close  (ec_open_close );

        cdplayer_event cd_detected (ec_cd_detected);

        cdplayer_event stop        (ec_stop       );

        cdplayer_event pause       (ec_pause      );

 

        player.transition ( player.get_state_instance(cdplayer::sid_empty) );

 

        player.notify ( &cd_detected );

        player.notify ( &play        );

        player.notify ( &pause       );

        player.notify ( &stop        );

        player.notify ( &open_close  );

        player.notify ( &stop        );

        player.notify ( &play        );

        player.notify ( &open_close  );

 

        player.notify ( &open_close  );

        player.notify ( &cd_detected );

        player.notify ( &play        );

 

        return 0;

}

 

/////////////////////////////////////////////////////////////////////////////

//

// result

//

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

/*

transition: empty

        on_entry: empty

                notify: cd_detected

                        action: store_cd_information

transition: empty ->  stopped

        on_exit : empty

        on_entry: stopped

                notify: play

                        action: start_playback

transition: stopped ->  playing

        on_exit : stopped

        on_entry: playing

                notify: pause

                        action: pause_playback

transition: playing ->  paused

        on_exit : playing

        on_entry: paused

                notify: stop

                        action: stop_playback

transition: paused ->  stopped

        on_exit : paused

        on_entry: stopped

                notify: open_close

                        action: open_drawer

transition: stopped ->  open

        on_exit : stopped

        on_entry: open

                notify: stop

                notify: play

                notify: open_close

                        action: close_drawer

                        action: collect_cd_information

transition: open ->  empty

        on_exit : open

        on_entry: empty

                notify: open_close

                        action: open_drawer

transition: empty ->  open

        on_exit : empty

        on_entry: open

                notify: cd_detected

                notify: play

계속하려면아무키나누르십시오. . .

*/

 

 

Posted by 셈말짓기 :

class object
{
private:
 typedef unsigned int uint_t;
 typedef void (object::*object_proc)(uint_t param);

 std::map<uint_t, object::object_proc> _lookup_of_object_proc;

public:
 uint_t _value;

public:
 void initialize (void)
 {
  _lookup_of_object_proc[0] = &object::test_1;
  _lookup_of_object_proc[1] = &object::test_2;
 }

 void test_1 (uint_t param)
 {
  printf ("test_1 = %d %d \r\n",_value, param);
 }

 void test_2 (uint_t param)
 {
  printf ("test_2 = %d %d \r\n", _value, param);
 }

 void run (uint_t id, uint_t value)
 {
  object_proc proc = _lookup_of_object_proc[id];

  if (proc)
  {
   (this->*proc) (value);
  }
 }
};

int _tmain(int argc, _TCHAR* argv[])
{
 HRESULT hRes = ::CoInitialize(NULL);

 assert(SUCCEEDED(hRes));


 object a,b;

 a.initialize();
 b.initialize();

 a._value = 10;
 b._value = 20;

 a.run (0, 1);
 a.run (1, 2);

 b.run (0, 1);
 b.run (1, 2);

 ::CoUninitialize();

 return 0;
}



---------------------------------------------------------
test_1 = 10 1
test_2 = 10 2
test_1 = 20 1
test_2 = 20 2
계속하려면 아무 키나 누르십시오 . . .

Posted by 셈말짓기 :


std::for_each(m_Module.begin(), m_Module.end(), DeleteWindowObject<CVMEModuleWidget*>); 

template <typename TYPE>
static void DeleteWindowObject (TYPE p)
{
 p->DestroyWindow();
 delete p;
}

template <typename TYPE>
static void DeletePointer (TYPE p)
{
 delete p;
}

template <typename TYPE>
static void DeleteArrayPointer (TYPE p)
{
 delete []p;

 template <typename TYPE>
 static void delete_pointer_of_std_pair_second (TYPE p)
 {
  delete p.second;
 }

Posted by 셈말짓기 :

# SVN 사용시 아래 파일은 무시하도록 설정한다.

1. 위치
[TortoiseSVN 설정 / 일반 / Subversion / 제외/무시 패턴(&P)]

2. 기본값
*.o *.lo *.la *.al .libs *.so *.so.[0-9]* *.a *.pyc *.pyo *.rej *~ #*# .#* .*.swp .DS_Store

3. 추가 내용
Thumbs.db *.map *.exe *.res mt.dep BuildLog.htm *.ilk *.exe.embed.manifest *.exe.intermediate.manifest *.obj *.pch *.pdb *.idb *.user *.aps *.ncb *.suo

4. 추가 후 내용
Thumbs.db *.map *.exe *.res mt.dep BuildLog.htm *.ilk *.exe.embed.manifest *.exe.intermediate.manifest *.obj *.pch *.pdb *.idb *.user *.aps *.ncb *.suo *.o *.lo *.la *.al .libs *.so *.so.[0-9]* *.a *.pyc *.pyo *.rej *~ #*# .#* .*.swp .DS_Store


# SVN 과 연결을 해제 하면서 .svn하위 파일을 삭제 하는 쉘 스크립트
[Delete SVN Folders.reg]
----------------------------------------------------------------------------------------------------
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""
----------------------------------------------------------------------------------------------------

Posted by 셈말짓기 :


static const WORD MAX_CONSOLE_LINES = 500;

#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>

void RedirectIOToConsole()
{
 int hConHandle;
 long lStdHandle;

 CONSOLE_SCREEN_BUFFER_INFO coninfo;

 FILE *fp;

 // allocate a console for this app

 AllocConsole();

 // set the screen buffer to be big enough to let us scroll text
 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);

 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);

 // redirect unbuffered STDOUT to the console
 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
 fp = _fdopen( hConHandle, "w" );
 *stdout = *fp;
 setvbuf( stdout, NULL, _IONBF, 0 );

 // redirect unbuffered STDIN to the console
 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
 fp = _fdopen( hConHandle, "r" );
 *stdin = *fp;
 setvbuf( stdin, NULL, _IONBF, 0 );

 // redirect unbuffered STDERR to the console
 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
 fp = _fdopen( hConHandle, "w" );
 *stderr = *fp;
 setvbuf( stderr, NULL, _IONBF, 0 );

 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
 // point to console as well
 std::ios::sync_with_stdio();
}

Posted by 셈말짓기 :

static_cast
It is able to do the reverse of what an implicit conversion can do. Meaning: narrow (long -> int), widen (int -> long), base-to-derived, void*-to-T* for example. You can't use it for the stuff that an reversed implicit conversion cannot do. (I.e you cannot cast an int* into int).


dynamic_cast
It is used to cast a base pointer into a derived pointer. If the base pointer doesn't point to an object of the type of the derived, it returns 0.
It is used to cast a base reference into a derived reference. If the reference isn't pointing to an object of the derived, it throws std::bad_cast.
It can be considered the checked cast equivalent to static_cast, in that it checks whether the object pointed to really is of the derived type.


reinterpret_cast

It is used to cast a pointer type to a wide enough integral type and back to the original pointer type.
It is used to cast between pointer types of incompatible types (int* to double* for example). The result of that mapping is unspecified, but it's possible to do so.


const_cast

It is used to cast away const or volatile. It is used in the rare cases when you have a originally non-const object, which is pointed to by a pointer-to-const or referenced to by a reference-to-const. Casting away constness is considered evil and should not be done if it can be avoided.

Posted by 셈말짓기 :

Windows Sleep(1)은 1 msec을 안 놀아주고 약 10 msec를 놀아 준다.
그래서 대충 1 msec 놀겠금 구현한 함수....
하지만, 태스크 메니저보면 cpu점유을은 100%으로 보이긴 하나 괜춚다!
어차피 열나게 컨텍스트 스위칭 할테니...

extern "C" int delay (unsigned int time)

{

        if (time<10 && time!=0)

        {

               LARGE_INTEGER start;

               LARGE_INTEGER end;

               LARGE_INTEGER frequency;

               LARGE_INTEGER differance;

 

               long double   duration;

       

               QueryPerformanceFrequency(&frequency);

               QueryPerformanceCounter  (&start);

               while (1)

               {

                       Sleep (0); // or SwitchToThread();

 

                       QueryPerformanceCounter (&end);

       

                       differance.QuadPart = end.QuadPart - start.QuadPart;

                       duration            = (long double)(differance.QuadPart*1000/frequency.QuadPart);

 

                       if (time <= duration)

                       {

                              break;

                       }

               }
        }

        else

        {

               Sleep (time);

        }

       

        return 0;

}

 

Posted by 셈말짓기 :
코드프로젝트에 있는 코드 고쳐서 좀 만들어 봤습니다.
전 임베디드를 해서 해당 타겟이 int64를 지원안해서 고쳐보았습니다.
원본 소스는 http://www.codeproject.com/KB/IP/csntp.aspx 이지만 모양새는 많이 다릅니다. -_-;


// sntp.cpp : 콘솔응용프로그램에대한진입점을정의합니다.

//

 

#include "stdafx.h"

 

#include <time.h>

 

 

#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

 

namespace sntp

{

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

#if defined ( WIN32 )

#        define __little_endian__ 1

#endif

#if defined ( VXWORKS )

#        define __big_endian__    1

#endif

 

#define __sntp_debug_print__ 1

 

//===========================================================================

typedef unsigned int       uint32_t;

typedef unsigned short int uint16_t;

typedef unsigned char      uint8_t;

 

typedef signed int         int32_t;

typedef signed short int   int16_t;

typedef signed char        int8_t;

 

//===========================================================================

typedef struct _system_time_t

{

    uint16_t year         ;

    uint16_t month        ;

    uint16_t day_of_week  ;

    uint16_t day          ;

    uint16_t hour         ;

    uint16_t minute       ;

    uint16_t second       ;

    uint16_t milliseconds ;

} system_time_t;

 

typedef struct _timestamp_t

{

    uint32_t seconds          ;

    uint32_t seconds_fraction ;

} timestamp_t;

 

typedef struct _ntp_server_response_t

{

         int leap_indicator;

         // 0: no warning

         // 1: last minute in day has 61 seconds

         // 2: last minute has 59 seconds

         // 3: clock not synchronized

 

         int stratum;

         //      0: unspecified or unavailable

         //      1: primary reference (e.g., radio clock)

         //   2-15: secondary reference (via NTP or SNTP)

         // 16-255: reserved

 

         timestamp_t originate_timestamp  ; // T1: Time when the request was sent from the client to the SNTP server

         timestamp_t receive_timestamp    ; // T2: Time when the request was received by the server

         timestamp_t transmit_timestamp   ; // T3: Time when the server sent the request back to the client

         timestamp_t destination_timestamp; // T4: Time when the reply was received by the client

         double      round_trip_delay     ; // Round trip time in seconds

         double      local_clock_offset   ; // Local clock offset relative to the server

} ntp_server_response_t;

 

// Ref. RFC 2030 - Simple Network Time Protocol (SNTP) Version 4 for IPv

// http://www.faqs.org/rfcs/rfc2030.html

typedef struct _ntp_packet_t

{

#if defined ( __little_endian__ )

    uint8_t     mode                : 3 ;

    uint8_t     vn                  : 3 ;

    uint8_t     li                  : 2 ;

#else                                                                    

    uint8_t     li                  : 2 ;

    uint8_t     vn                  : 3 ;

    uint8_t     mode                : 3 ;

#endif                                                                   

    uint8_t     stratum                 ;

    uint8_t     poll                    ;

    uint8_t     precision               ;

    uint32_t    root_delay              ;

    uint32_t    root_dispersion         ;

    uint32_t    reference_identifier    ;

    timestamp_t reference_timestamp     ;

    timestamp_t originate_timestamp     ;

    timestamp_t receive_timestamp       ;

    timestamp_t transmit_timestamp      ;

} ntp_packet_t;

 

typedef unsigned int socket_handle_t;

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

#include "sntp.inl"

static const uint16_t _socket_timeout      =    1000;

static const uint16_t _socket_default_port =     123;

static const int32_t  _julian_1900_01_01   = 2415021;

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

inline socket_handle_t socket_create (int af, int type, int protocol)

{

         return (socket_handle_t)socket (af, type, protocol);

}

 

inline int socket_close (socket_handle_t s)

{

         return closesocket (s);

}

 

inline int socket_connect (socket_handle_t s, const struct sockaddr* name, int namelen)

{

         return connect (s, name, namelen);

}

 

inline int socket_recv (socket_handle_t s, char* buf, int len, int flags)

{

         return recv (s, buf, len, flags);

}

 

inline int socket_send (socket_handle_t s, const char* buf, int len, int flags)

{

         return send (s, buf, len, flags);

}

 

bool socket_make_address (

         struct sockaddr_in* sa,

         const char*         address,

         uint16_t            port   ,

         uint16_t            family = AF_INET)

{

         memset (sa, 0, sizeof(struct sockaddr_in));

 

         sa->sin_family      = family;

         sa->sin_addr.s_addr = inet_addr(address);

 

         if (sa->sin_addr.s_addr==INADDR_NONE)

         {

                  struct hostent* host;

 

                  host = gethostbyname(address);

                  if (host != 0)

                  {

                           sa->sin_addr.s_addr = ((struct in_addr*)host->h_addr)->s_addr;

                  }

                  else

                  {

                           return false;

                  }

         }

 

         sa->sin_port = htons((uint16_t)port);

 

         return true;

}

 

//===========================================================================

void convert_gregorian_to_julian (uint16_t year, uint16_t month, uint16_t day, int32_t& julian)

{

         int32_t y ;

         int32_t m ;

         int32_t d ;

         int32_t c ;

         int32_t ya;

        

         y = (int32_t) year ;

         m = (int32_t) month;

         d = (int32_t) day  ;

        

         if (m > 2)

         {

                  m = m - 3;

         }

         else

         {

                  m = m + 9;

                  y = y - 1;

         }

        

         c  = y / 100;

         ya = y - 100 * c;

        

         julian = (146097L * c) / 4 + (1461L * ya) / 4 + (153L * m + 2) / 5 + d + 1721119L;

}

 

void convert_julian_to_gregorian (int32_t julian, uint16_t& year, uint16_t& month, uint16_t& day)

{

         int32_t j;

         int32_t y;

         int32_t d;

         int32_t m;

        

         j = julian - 1721119;

         y = (4 * j - 1) / 146097;

         j = 4 * j - 1 - 146097 * y;

         d = j / 4;

         j = (4 * d + 3) / 1461;

         d = 4 * d + 3 - 1461 * j;

         d = (d + 4) / 4;

         m = (5 * d - 3) / 153;

         d = 5 * d - 3 - 153 * m;

         d = (d + 5) / 5;

         y = 100 * y + j;

 

         if (m < 10)

         {

                  m = m + 3;

         }

         else

         {

                  m = m - 9;

                  y = y + 1;

         }

 

         year  = (uint16_t) y;

         month = (uint16_t) m;

         day   = (uint16_t) d;

}

 

uint32_t convert_milliseconds_to_seconds_fraction (uint16_t milliseconds)

{

#if 1

         // 4294967296 == 0x1 0000 0000 (2^32)

         return (uint32_t) (4294967296.0 * milliseconds / 1000);

#else   

         return ( milliseconds<1000 )? _seconds_fraction_table[milliseconds] : _seconds_fraction_table[999];

#endif  

}

 

uint16_t convert_seconds_fraction_to_milliseconds (uint32_t seconds_fraction)

{

#if 1

         static const double ratio        = (((double)1000.0)/4294967296.0);

         double              milliseconds = ((double)seconds_fraction) * ratio;

#else

         static const double ratio        = (((double)1000.0)/0xFFFFFFFF);

         double              milliseconds = ((double)seconds_fraction) * ratio + 0.5;

#endif  

         return (uint16_t)(milliseconds);

}

 

void make_timestamp (

         timestamp_t& timestamp        ,

         uint16_t     year             ,

         uint16_t     month        = 1 ,

         uint16_t     day          = 1 ,

         uint16_t     hour         = 0 ,

         uint16_t     minute       = 0 ,

         uint16_t     second       = 0 ,

         uint16_t     milliseconds = 0 )

{

         int32_t julian;

        

         convert_gregorian_to_julian (year,month,day, julian);

         julian = julian - _julian_1900_01_01;

        

         timestamp.seconds          = (julian*24*60*60) + (hour*60*60) + (minute*60) + second;

         timestamp.seconds_fraction = convert_milliseconds_to_seconds_fraction (milliseconds);

}

 

//===========================================================================

void get_current_timestamp (timestamp_t& timestamp)

{

#if 0

         static const uint32_t from_1900_to_1970 = 86400U * (365U*70U + 17U);

        

         uint32_t t;

        

         t = (uint32_t)time (0); // time(): 1970-01-01 based

         t+= from_1900_to_1970;

        

         timestamp.seconds          = t;

         timestamp.seconds_fraction = 0;

#else

         SYSTEMTIME st;

        

         GetSystemTime (&st);

         make_timestamp (timestamp,

                  st.wYear        ,

                  st.wMonth       ,

                  //st.wDayOfWeek   ,

                  st.wDay         ,

                  st.wHour        ,

                  st.wMinute      ,

                  st.wSecond      ,

                  st.wMilliseconds);

#endif           

}

 

//===========================================================================

void convert_timestamp_to_system_time (const timestamp_t& timestamp, system_time_t& system_time)

{

         uint32_t julian;

        

         system_time.hour         = (timestamp.seconds/3600)%24;

         system_time.minute       = (timestamp.seconds/60  )%60;

         system_time.second       = (timestamp.seconds     )%60;

        

         system_time.milliseconds = convert_seconds_fraction_to_milliseconds (timestamp.seconds_fraction);

 

         julian = timestamp.seconds/86400 + _julian_1900_01_01;

        

         convert_julian_to_gregorian (julian, system_time.year, system_time.month, system_time.day);

         system_time.day_of_week = ((julian+1) % 7);

}

 

void print_timestamp (const timestamp_t& timestamp)

{

         system_time_t system_time;

         const char*   day_of_week_string[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

        

         convert_timestamp_to_system_time (timestamp, system_time);

        

         printf ("%4d-%02d-%02d(%s) %02d:%02d:%02d.%03d \r\n",

                  system_time.year        ,

                  system_time.month       ,

                  system_time.day         ,

                  day_of_week_string[system_time.day_of_week],

                 

                  system_time.hour        ,

                  system_time.minute      ,

                  system_time.second      ,

                  system_time.milliseconds);

}

 

//===========================================================================

bool client_request (

         ntp_server_response_t& response        ,

         struct sockaddr_in*    server_address  ,

         uint32_t               milisec_timeout = _socket_timeout)

{

    socket_handle_t socket_handle;

    struct timeval  timeout;

    fd_set          fds;

    int             result;

   

    socket_handle = socket_create (AF_INET, SOCK_DGRAM, 0);

    if (socket_handle < 0)

    {

        return false;

    }

   

    result = socket_connect (socket_handle, (struct sockaddr*) server_address, sizeof(struct sockaddr_in));

    if (result < 0)

    {

        socket_close(socket_handle);

        return false;

    }

   

 

         // ntp packet

    ntp_packet_t ntp_packet;

    timestamp_t  timestamp ;

 

    memset(&ntp_packet, 0, sizeof(ntp_packet));

    ntp_packet.vn   = 4;

    ntp_packet.mode = 3;

    ntp_packet.li   = 0;

   

    get_current_timestamp (timestamp);

    ntp_packet.transmit_timestamp.seconds           = htonl(timestamp.seconds         );

    ntp_packet.transmit_timestamp.seconds_fraction  = htonl(timestamp.seconds_fraction);

 

         // T1

    response.originate_timestamp.seconds          = timestamp.seconds         ;

    response.originate_timestamp.seconds_fraction = timestamp.seconds_fraction;

 

        

    result = socket_send (socket_handle, (char*)&ntp_packet, sizeof(ntp_packet), 0);

    if ( result != sizeof(ntp_packet) )

    {

        socket_close (socket_handle);

        return false;

    }

        

    FD_ZERO (&fds);

    FD_SET  (socket_handle, &fds);

    timeout.tv_sec  =  milisec_timeout / 1000;

    timeout.tv_usec = (milisec_timeout % 1000) * 1000;

    result = select (socket_handle+1, &fds, NULL, NULL, &timeout);

   

    if ( result == 0 || result == -1 )

    {

        socket_close(socket_handle);

        return false;

    }

   

 

         // T4

         get_current_timestamp (timestamp);

    response.destination_timestamp.seconds          = timestamp.seconds         ;

    response.destination_timestamp.seconds_fraction = timestamp.seconds_fraction;

 

   

    result = socket_recv (socket_handle, (char*)&ntp_packet, sizeof(ntp_packet), 0);

    if ( result != sizeof(ntp_packet) )

    {

        socket_close(socket_handle);

        return false;

    }

 

    socket_close (socket_handle);

 

   

         // T2/3

    response.receive_timestamp.seconds           = ntohl(ntp_packet.receive_timestamp.seconds          );

    response.receive_timestamp.seconds_fraction  = ntohl(ntp_packet.receive_timestamp.seconds_fraction );

    response.transmit_timestamp.seconds          = ntohl(ntp_packet.transmit_timestamp.seconds         );

    response.transmit_timestamp.seconds_fraction = ntohl(ntp_packet.transmit_timestamp.seconds_fraction);

        

         //-----------------------------------------------------------------------

         // Timestamp Name          ID   When Generated

         //-----------------------------------------------------------------------

         // Originate Timestamp     T1   time request sent by client

         // Receive Timestamp       T2   time request received by server

         // Transmit Timestamp      T3   time reply sent by server

         // Destination Timestamp   T4   time reply received by client

        

         /*

         The roundtrip delay(d)

    d = (T4 - T1) - (T2 - T3)    

        

         local clock offset t are defined as

         t = ((T2 - T1) + (T3 - T4)) / 2.

         */     

 

         static const uint32_t NTP_DIFF  = 2208988800U;      // 1970-01-01

         static const double   NTP_SCALE = 2.3283064365e-10; // 2^-32

 

         double t1,t2,t3,t4;

 

         t1=response.originate_timestamp  .seconds-NTP_DIFF + response.originate_timestamp  .seconds_fraction * NTP_SCALE;

         t2=response.receive_timestamp    .seconds-NTP_DIFF + response.receive_timestamp    .seconds_fraction * NTP_SCALE;

         t3=response.transmit_timestamp   .seconds-NTP_DIFF + response.transmit_timestamp   .seconds_fraction * NTP_SCALE;

         t4=response.destination_timestamp.seconds-NTP_DIFF + response.destination_timestamp.seconds_fraction * NTP_SCALE;

        

         response.round_trip_delay   =  (t4 - t1) - (t2 - t3);

         response.local_clock_offset = ((t2 - t1) + (t3 - t4)) * 0.5;

 

         //-----------------------------------------------------------------------

 

         response.stratum        = ntp_packet.stratum;

         response.leap_indicator = ntp_packet.li;

 

#if __sntp_debug_print__

         printf ("# sntp_debug \r\n");

    printf ("  li                  = %d     \r\n", ntp_packet.li                   );

    printf ("  vn                  = %d     \r\n", ntp_packet.vn                   );

    printf ("  mode                = %d     \r\n", ntp_packet.mode                 );

    printf ("  stratum             = 0x%02x \r\n", ntp_packet.stratum              );

    printf ("  poll                = 0x%02x \r\n", ntp_packet.poll                 );

    printf ("  precision           = 0x%02x \r\n", ntp_packet.precision            );

    printf ("  root_delay          = 0x%08x \r\n", ntp_packet.root_delay           );

    printf ("  root_dispersion     = 0x%08x \r\n", ntp_packet.root_dispersion      );

    printf ("  reference_identifier= 0x%08x \r\n", ntp_packet.reference_identifier );

 

         printf ("  reference_timestamp = ");

    timestamp.seconds         =ntohl(ntp_packet.reference_timestamp.seconds         );

    timestamp.seconds_fraction=ntohl(ntp_packet.reference_timestamp.seconds_fraction);

    print_timestamp (timestamp);

 

         printf ("  originate_timestamp = ");

    timestamp.seconds         =ntohl(ntp_packet.originate_timestamp.seconds         );

    timestamp.seconds_fraction=ntohl(ntp_packet.originate_timestamp.seconds_fraction);

    print_timestamp (timestamp);

 

         printf ("  receive_timestamp   = ");

    timestamp.seconds         =ntohl(ntp_packet.receive_timestamp  .seconds         );

    timestamp.seconds_fraction=ntohl(ntp_packet.receive_timestamp  .seconds_fraction);

    print_timestamp (timestamp);

 

         printf ("  transmit_timestamp  = ");

         timestamp.seconds         =ntohl(ntp_packet.transmit_timestamp .seconds         );

    timestamp.seconds_fraction=ntohl(ntp_packet.transmit_timestamp .seconds_fraction);

    print_timestamp (timestamp);

 

         printf ("\r\n");

        

         printf ("  round_trip_delay    = %f \r\n", response.round_trip_delay  );

         printf ("  local_clock_offset  = %f \r\n", response.local_clock_offset);

#endif

 

    return true;

}

 

bool get_time (timestamp_t& adjusted_time, const char* address, uint16_t port = _socket_default_port)

{

         ntp_server_response_t response;

         struct sockaddr_in    sa;

        

         if (false==socket_make_address (&sa, address, port))

                  return false;

 

         if (false==client_request(response, &sa))

                  return false;

                 

         uint32_t    offset_second       ;

         uint32_t    offset_milliseconds ;

        

         uint32_t    current_milliseconds;

         uint32_t    current_second      ;

        

         timestamp_t current_timestamp   ;

        

         double      offset;

         bool        offset_negative;

                 

        

         offset          = (0>response.local_clock_offset)? -1.0*response.local_clock_offset : response.local_clock_offset;

         offset_negative = (0>response.local_clock_offset)? true : false;

        

         offset_second       = (uint32_t)( offset                    );

         offset_milliseconds = (uint32_t)((offset-offset_second)*1000);

        

        

         get_current_timestamp (current_timestamp);

        

         current_second       = current_timestamp.seconds;

         current_milliseconds = convert_seconds_fraction_to_milliseconds (current_timestamp.seconds_fraction);

        

         if (offset_negative)

         {

                  if (current_milliseconds<offset_milliseconds)

                  {

                           current_milliseconds = 1000+current_milliseconds-offset_milliseconds;

                           current_second       = current_second-offset_second - 1;

                  }

                  else

                  {

                           current_milliseconds = current_milliseconds-offset_milliseconds;

                           current_second       = current_second-offset_second;

                  }

         }

         else

         {

                  current_milliseconds+=offset_milliseconds;

 

                  current_second       = current_second+offset_second + (current_milliseconds/1000);

                  current_milliseconds = current_milliseconds%1000;

         }

        

         current_timestamp.seconds          = current_second;

         current_timestamp.seconds_fraction = convert_milliseconds_to_seconds_fraction (current_milliseconds);

        

         memcpy (&adjusted_time, &current_timestamp, sizeof(adjusted_time));

        

         return true;

}

 

//===========================================================================

} // end of "namespace sntp { "

 

 

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

 

void TRACE (const TCHAR* lpFormatStr, ...)

{

         TCHAR   szBuffer[256];

         va_list args;

 

         va_start  (args, lpFormatStr);

#pragma warning( push )

#pragma warning( disable : 4996 )

         _vsntprintf (szBuffer, 256, lpFormatStr, args);

#pragma warning( pop )

         va_end    (args);     

 

         OutputDebugStringA (szBuffer);

         printf (szBuffer);

}

 

class adjust_settime_priviledge

{

public:

         HANDLE           _token_handle    ;

         TOKEN_PRIVILEGES _token_privileges;

         BOOL             _taken_priviledge;

 

public:

         adjust_settime_priviledge ():

                  _token_handle    (0),

                  _taken_priviledge(FALSE)

         {

                  ZeroMemory(&_token_privileges, sizeof(TOKEN_PRIVILEGES));

         }

        

         ~adjust_settime_priviledge ()

         {

                  revert_settime_priviledge ();

         }

        

public:

         BOOL enable_settime_priviledge (void)

         {

                  BOOL opentoken;

                  BOOL success  ;

 

 

                  _taken_priviledge = FALSE;

 

                  opentoken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &_token_handle);

                  if (!opentoken)

                  {

                           if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)

                           {

                                   //Must be running on 95 or 98 not NT. In that case just ignore the error

                                   SetLastError(ERROR_SUCCESS);

                                   return TRUE;

                           }

                           TRACE(_T("Failed to get Adjust priviledge token\n"));

                           return FALSE;

                  }

                 

                  ZeroMemory(&_token_privileges, sizeof(TOKEN_PRIVILEGES));

                  if (!LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &_token_privileges.Privileges[0].Luid))

                  {

                           TRACE(_T("Failed in callup to lookup priviledge\n"));

                           return FALSE;

                  }

                 

                  _token_privileges.PrivilegeCount            = 1;

                  _token_privileges.Privileges[0].Attributes |= SE_PRIVILEGE_ENABLED;

                 

                  _taken_priviledge = TRUE;

 

                  success = AdjustTokenPrivileges(_token_handle, FALSE, &_token_privileges, 0, NULL, 0);

                  if (!success)

                  {

                           TRACE(_T("Failed to adjust SetTime priviledge\n"));

                  }

                 

                  return success;

         }

 

         void revert_settime_priviledge (void)

         {

                  if (_taken_priviledge)

                  {

                           _token_privileges.Privileges[0].Attributes &= (~SE_PRIVILEGE_ENABLED);

                          

                           if (!AdjustTokenPrivileges(_token_handle, FALSE, &_token_privileges, 0, NULL, 0))

                           {

                                   TRACE(_T("Failed to reset SetTime priviledge\n"));

                           }

                  }

         }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

         WSADATA           wsadata;

         sntp::timestamp_t adjusted_time;

        

         WSAStartup(MAKEWORD(2,2), &wsadata);

 

 

//       if (true==sntp::get_time (adjusted_time, "time.windows.com"))

         if (true==sntp::get_time (adjusted_time, "time.nist.gov"))

//       if (true==sntp::get_time (adjusted_time, "time.nuri.net"))

         {

                  adjust_settime_priviledge asp;

                 

                  if (TRUE==asp.enable_settime_priviledge ())

                  {

                           sntp::system_time_t st;

                          

                           convert_timestamp_to_system_time (adjusted_time, st);                          

                           SetSystemTime((SYSTEMTIME*)&st);

                          

                           printf ("\r\n# adjusted_time: ");

                           print_timestamp (adjusted_time);

                  }

         }

        

         WSACleanup();

        

         return 0;

}

 

결과



Posted by 셈말짓기 :

EXCEL EXPORT

2010. 10. 27. 16:23 from 셈말짓기/Windows

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE12\\MSO.DLL" \

        rename( "RGB", "MSORGB" ) \

        rename( "DocumentProperties","MSODocumentProperties" )

//using namespace Office;

 

#import "C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB"

//using namespace VBIDE;

 

#import "C:\\Program Files\\Microsoft Office\\OFFICE12\\EXCEL.EXE" \

        rename( "DialogBox", "ExcelDialogBox" ) \

        rename( "RGB", "ExcelRGB" ) \

        rename( "CopyFile", "ExcelCopyFile" ) \

        rename( "ReplaceText", "ExcelReplaceText" ) \

        exclude("IFont") \

        exclude("IPicture")

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

#include <string>

#include <cx/StringUtility.h>

 

/////////////////////////////////////////////////////////////////////////////

//===========================================================================

void Export_Excel_1 (void)

{

        std::string target_filepath_a = "D:\\a.xlsx";

 

 

        _bstr_t    target_filepath;

        _variant_t cell_item_value;

 

 

        target_filepath = cx::string_to_wstring( target_filepath_a ).c_str();

        cell_item_value = _bstr_t(L"2:2=Export_Excel_1");

 

 

        Excel::_ApplicationPtr pApplication;

        Excel::_WorkbookPtr    pWorkbook;

        Excel::_WorksheetPtr   pWorksheet;

       

        pApplication.CreateInstance    ( _T("Excel.Application") );

        pApplication->PutDisplayAlerts ( 0, VARIANT_FALSE );

        pApplication->Workbooks->Add   ( _variant_t ( Excel::xlWBATWorksheet ) );

        /*Excel::XlWBATemplate::xlWBATWorksheet*/

 

        pWorkbook  = pApplication->Workbooks->Item [1];

        pWorksheet = pWorkbook->Sheets->Item[1];

 

        pWorksheet->Cells->Item[2][2] = cell_item_value;

        pWorksheet->Cells->Item[2][3] = cell_item_value;

        pWorksheet->Cells->Item[2][4] = cell_item_value;

 

        pWorksheet->SaveAs ( target_filepath );

       

        pWorkbook->Close ( VARIANT_FALSE );

 

        pApplication->Quit ();

}

 

//===========================================================================

void Export_Excel_2 (void)

{

        std::string source_filepath_a = "D:\\a.xlsx";

        std::string target_filepath_a = "D:\\b.xlsx";

 

        _bstr_t    source_filepath;

        _bstr_t    target_filepath;

        _variant_t cell_item_value;

        _variant_t option ((long)DISP_E_PARAMNOTFOUND, VT_ERROR);

 

        source_filepath = cx::string_to_wstring( source_filepath_a ).c_str();

        target_filepath = cx::string_to_wstring( target_filepath_a ).c_str();

        cell_item_value = _bstr_t(L"3:2=Expor_tExcel_2");

 

 

        Excel::_ApplicationPtr pApplication;

        Excel::_WorkbookPtr    pWorkbook;

        Excel::_WorksheetPtr   pWorksheet;

 

 

        pApplication.CreateInstance( _T("Excel.Application") );

        pApplication->PutDisplayAlerts ( 0, VARIANT_FALSE );

 

        pWorkbook  = pApplication->Workbooks->Open( source_filepath,

                     option, option, option, option, option,

                     option, option, option, option, option, option, option );

        pWorksheet = pWorkbook->Sheets->Item[ 1 ];

 

        pWorksheet->Name = L"Export_Excel_2";

        pWorksheet->Cells->Item[3][2] = cell_item_value;

        pWorksheet->Cells->Item[3][3] = cell_item_value;

        pWorksheet->Cells->Item[3][4] = cell_item_value;

 

        pWorksheet->Cells->Item[4][2] = cell_item_value;

        pWorksheet->Cells->Item[4][3] = cell_item_value;

        pWorksheet->Cells->Item[4][4] = cell_item_value;

 

#if 1 // overwrite

        pWorkbook->Close ( VARIANT_TRUE );

#else

        pWorksheet->SaveAs ( target_filepath );

 

        pWorkbook->Close ( VARIANT_FALSE );

#endif

 

        pApplication->Quit ();

}

 

Posted by 셈말짓기 :

class CTFMForm : public CDialogImpl<CTFMForm>
{
public:
 enum { IDD = IDD_TFM };

 BOOL PreTranslateMessage(MSG* pMsg)
 {
  return CWindow::IsDialogMessage(pMsg);
 }

 BEGIN_MSG_MAP(CTFMForm)
  MESSAGE_HANDLER      (WM_INITDIALOG, OnInitDialog)
  MESSAGE_HANDLER      (WM_DESTROY,    OnDestroy   )
 END_MSG_MAP()

public:
 LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 {
  return 0;
 }

 LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
 {
  bHandled = FALSE;
  return 0;
 }
};

#include <atlscrl.h>
class CTFMView : public CScrollWindowImpl<CTFMView>
{
public:
 DECLARE_WND_CLASS(NULL)

 BOOL PreTranslateMessage(MSG* pMsg)
 {
  pMsg;
  return FALSE;
 }

 void DoPaint(CDCHandle dc)
 {
  //TODO: Add your drawing code here
 }

 BEGIN_MSG_MAP(CTFMView)
  MESSAGE_HANDLER (WM_CREATE,  OnCreate )
  MESSAGE_HANDLER (WM_DESTROY, OnDestroy)
  MESSAGE_HANDLER (WM_SIZE,    OnSize   )
  CHAIN_MSG_MAP   (CScrollWindowImpl<CTFMView>)
 END_MSG_MAP()

public:
 CTFMForm m_Form;
 CSize    m_FormSize;

public:
 LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
 {
  m_Form.Create(m_hWnd);
  
  CRect rc;
  m_Form.GetClientRect (&rc);
  m_FormSize.cx = rc.Width();
  m_FormSize.cy = rc.Height(); 
  
  SetScrollSize(m_FormSize.cx, m_FormSize.cy);

  bHandled = FALSE;
  return 0;
 }

 LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
 {
  bHandled = FALSE;

  return 0;
 }

 LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
 {
  CSize size;
  CSize newsize;

  size.cx = GET_X_LPARAM(lParam);
  size.cy = GET_Y_LPARAM(lParam);

  if (::IsWindow (m_Form))
  {
   if (size.cx>m_FormSize.cx)
   {
    newsize.cx = size.cx;
   }
   else
   {
    newsize.cx = m_FormSize.cx;
   }

   if (size.cy>m_FormSize.cy)
   {
    newsize.cy = size.cy;
   }
   else
   {
    newsize.cy = m_FormSize.cy;
   }

   m_Form.SetWindowPos (0,0,0,newsize.cx,newsize.cy,SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);

  }

  bHandled = FALSE;

  return 0;
 }
};

Posted by 셈말짓기 :

/////////////////////////////////////////////////////////////////////////////
//
// in MainFrame.H
// m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE);
//
/////////////////////////////////////////////////////////////////////////////

class C_WTLWINVIEW_View : public CWindowImpl<C_WTLWINVIEW_View>
{
public:
 DECLARE_WND_CLASS(NULL)

 BOOL PreTranslateMessage(MSG* pMsg)
 {
  pMsg;
  return FALSE;
 }

 BEGIN_MSG_MAP(C_WTLWINVIEW_View)
  MESSAGE_HANDLER(WM_PAINT, OnPaint)
 END_MSG_MAP()

// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)

 LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
 {
  CPaintDC dc(m_hWnd);

  //TODO: Add your drawing code here

  return 0;
 }
};

/////////////////////////////////////////////////////////////////////////////
//
// in MainFrame.H
// m_hWndClient = m_view.Create(m_hWnd);
//
/////////////////////////////////////////////////////////////////////////////
#include <atlscrl.h>
class C_WTLFORMVIEW_View : public CDialogImpl<C_WTLFORMVIEW_View>
{
public:
 enum { IDD = IDD_TEMPVIEW_FORM };

 BOOL PreTranslateMessage(MSG* pMsg)
 {
  return CWindow::IsDialogMessage(pMsg);
 }

 BEGIN_MSG_MAP(C_WTLFORMVIEW_View)
 END_MSG_MAP()
};


/////////////////////////////////////////////////////////////////////////////
//
// m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_HSCROLL | WS_VSCROLL, WS_EX_CLIENTEDGE);
// // replace with appropriate values for the app
// m_view.SetScrollSize(2000, 1000);
/////////////////////////////////////////////////////////////////////////////
class C_WTLSCROLLVIEW_View : public CScrollWindowImpl<C_WTLSCROLLVIEW_View>
{
public:
 DECLARE_WND_CLASS(NULL)

 BOOL PreTranslateMessage(MSG* pMsg)
 {
  pMsg;
  return FALSE;
 }

 void DoPaint(CDCHandle dc)
 {
  //TODO: Add your drawing code here
 }

 BEGIN_MSG_MAP(C_WTLSCROLLVIEW_View)
  CHAIN_MSG_MAP(CScrollWindowImpl<C_WTLSCROLLVIEW_View>)
 END_MSG_MAP()
};

Posted by 셈말짓기 :


// http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-mallocator.aspx
template <typename T> class Mallocator;

template <> class Mallocator<void>
{
public:
    typedef void*        pointer;
    typedef const void*  const_pointer;
    // reference to void members are impossible.
    typedef void         value_type;

public:
    template <class U> struct rebind { typedef pool_allocator<U> other; };
};   

template <typename T>
class Mallocator
{
public:
 // The following will be the same for virtually all allocators.
 typedef T*        pointer;
 typedef const T*  const_pointer;
 typedef T&        reference;
 typedef const T&  const_reference;
 typedef T         value_type;
 typedef size_t    size_type;
 typedef ptrdiff_t difference_type;

public:
 // Default constructor, copy constructor, rebinding constructor, and destructor.
 // Empty for stateless allocators.
 Mallocator()
 {
 }

 ~Mallocator()
 {
 }

 Mallocator(const Mallocator&)
 {
 }

public:
 // The following must be the same for all allocators.
 template <typename U> struct rebind { typedef Mallocator<U> other; };
 template <typename U> Mallocator(const Mallocator<U>&) {}

 // Returns true if and only if storage allocated from *this
 // can be deallocated from other, and vice versa.
 // Always returns true for stateless allocators.
 bool operator==(const Mallocator& other) const
 {
  return true;
 }

 bool operator!=(const Mallocator& other) const
 {
  return !(*this == other);
 }

public:
 size_t max_size() const
 {
  // The following has been carefully written to be independent of
  // the definition of size_t and to avoid signed/unsigned warnings.
  return (static_cast<size_t>(0) - static_cast<size_t>(1)) / sizeof(T);
 }

 T* address(T& r) const
 {
  return &r;
 }

 const T* address(const T& s) const
 {
  return &s;
 }

 void construct(T * const p, const T& t) const
 {
  void * const pv = static_cast<void *>(p);
  new (pv) T(t);
 }

 void destroy(T * const p) const // Defined below.
 {
  p->~T();
 }

 // The following will be different for each allocator.
 T * allocate(const size_t n) const
 {
  // Mallocator prints a diagnostic message to demonstrate
  // what it's doing. Real allocators won't do this.
  //std::cout << "Allocating " << n << (n == 1 ? " object" : " objects") << " of size " << sizeof(T) << "." << std::endl;
  printf ("allocate n=%d size=%d \r\n", n, sizeof(T));

  // The return value of allocate(0) is unspecified.
  // Mallocator returns NULL in order to avoid depending
  // on malloc(0)'s implementation-defined behavior
  // (the implementation can define malloc(0) to return NULL,
  // in which case the bad_alloc check below would fire).
  // All allocators can return NULL in this case.
  if (n == 0)
  {
   return NULL;
  }

  // All allocators should contain an integer overflow check.
  // The Standardization Committee recommends that std::length_error
  // be thrown in the case of integer overflow.
  if (n > max_size())
  {
   throw std::length_error("Mallocator<T>::allocate() - Integer overflow.");
  }

  // Mallocator wraps malloc().
  void * const pv = malloc(n * sizeof(T));

  // Allocators should throw std::bad_alloc in the case of memory allocation failure.
  if (pv == NULL)
  {
   throw std::bad_alloc();
  }

  return static_cast<T *>(pv);
 }

 void deallocate(T * const p, const size_t n) const
 {
  // Mallocator prints a diagnostic message to demonstrate
  // what it's doing. Real allocators won't do this.
  std::cout << "Deallocating " << n << (n == 1 ? " object" : "objects") << " of size " << sizeof(T) << "." << std::endl;

  // Mallocator wraps free().
  free(p);
 }

 // The following will be the same for all allocators that ignore hints.
 template <typename U> T * allocate(const size_t n, const U * /* const hint */) const
 {
  return allocate(n);
 }

 // Allocators are not required to be assignable, so
 // all allocators should have a private unimplemented
 // assignment operator. Note that this will trigger the
 // off-by-default (enabled under /Wall) warning C4626
 // "assignment operator could not be generated because a
 // base class assignment operator is inaccessible" within
 // the STL headers, but that warning is useless.
private:
 Mallocator& operator=(const Mallocator&);
};

Posted by 셈말짓기 :

#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console")
Posted by 셈말짓기 :

char* sitoa (char* a, int i)  
{  
 int   sign=0;  
 int   temp=0;  
 char  buf[16];  
 char* ptr;   

 ptr = buf;   

 /* zero then return */ 
 if( i )  
 {  
  /* make string in reverse form */ 
  if( i < 0 )
  {   
   i = ~i + 1;   
   sign++;
  }  
  while( i )
  {   
   *ptr++ = (i % 10) + '0';   
   i = i / 10;
  }  
  if(sign)  
  {
   *ptr++ = '-';  
  }
  *ptr = '\0';   

  /* copy reverse order */ 
  for( i=0; i < (int)strlen(buf); i++ )  
  {
   *a++ = buf[strlen(buf)-i-1];  
  }
 }      
 else
 {
  *a++ = '0';   
 }

 return a;  
}   

char* uitoa (char *a, unsigned int i)  
{  
 int   sign=0;  
 int   temp=0;  
 char  buf[16];  
 char* ptr;   

 ptr = buf;   

 /* zero then return */ 
 if( i )  
 {  
  while( i )
  {   
   *ptr++ = (i % 10) + '0';   
   i = i / 10;
  }  
  *ptr = '\0';   

  /* copy reverse order */ 
  for( i=0; i < (int)strlen(buf); i++ )  
  {
   *a++ = buf[strlen(buf)-i-1];  
  }
 }      
 else
 {
  *a++ = '0';   
 }

 return a;  
}   

char* htoa( char *a, unsigned int x, int opt)  
{  
 int   i;  
 int   sign=0;  
 int   temp=0;  
 char  buf[16];  
 char* ptr;   

 ptr = buf;   

 /* zero then return */ 
 if( x )  
 {  
  /* make string in reverse form */ 
  while( x )  
  {
   *ptr++ = (x&0x0f)<10 ? (x&0x0f)+'0' : (x&0x0f)-10+opt; x>>= 4;
  }   

  *ptr = '\0';   

  /* copy reverse order */ 
  for( i=0; i < (int)strlen(buf); i++ )  
  {
   *a++ = buf[strlen(buf)-i-1];  
  }
 }  
 else
 {
  *a++ = '0';   
 }
 return a;  
}

char * ltoa (long val, char *buf, unsigned radix)
{
 char *p;  /* pointer to traverse string */
 char *firstdig;  /* pointer to first digit */
 char temp;       /* temp char */
 unsigned digval; /* value of digit */

 p = buf;

 if (radix == 10 && val < 0) {
  /* negative, so output '-' and negate */
  *p++ = '-';
  val = (unsigned long)(-(long)val);
 }

 firstdig = p;    /* save pointer to first digit */

 do {
  digval = (unsigned) (val % radix);
  val /= radix;       /* get next digit */

  /* convert to ascii and store */
  if (digval > 9)
   *p++ = (char) (digval - 10 + 'a');  /* a letter */
  else
   *p++ = (char) (digval + '0');       /* a digit */
 } while (val > 0);

 /* We now have the digit of the number in the buffer, but in reverse
 order.  Thus we reverse them now. */

 *p-- = '\\0';     /* terminate string; p points to last digit */

 do {
  temp = *p;
  *p = *firstdig;
  *firstdig = temp;   /* swap *p and *firstdig */
  --p;
  ++firstdig;  /* advance to next two digits */
 } while (firstdig < p); /* repeat until halfway */

 return buf;
}


char *ftoa(float f, int *status)
{
 typedef union
 {
  long  L;
  float F;
 } LF_t;

 long  mantissa, int_part, frac_part;
 short exp2;

 LF_t  x;
 char* p;
 

 static char outbuf[15];


 *status = 0;
 if (f == 0.0)
 {
  outbuf[0] = '0';
  outbuf[1] = '.';
  outbuf[2] = '0';
  outbuf[3] =  0;
  return outbuf;
 }
 x.F = f;

 exp2      = (unsigned char)(x.L >> 23) - 127;
 mantissa  = (x.L & 0xFFFFFF) | 0x800000;
 frac_part = 0;
 int_part  = 0;

 if (exp2 >= 31)
 {
  *status = _FTOA_TOO_LARGE;
  return 0;
 }
 else if (exp2 < -23)
 {
  *status = _FTOA_TOO_SMALL;
  return 0;
 }
 else if (exp2 >= 23)
 {
  int_part = mantissa << (exp2 - 23);
 }
 else if (exp2 >= 0)
 {
  int_part = mantissa >> (23 - exp2);
  frac_part = (mantissa << (exp2 + 1)) & 0xFFFFFF;
 }
 else /* if (exp2 < 0) */
 {
  frac_part = (mantissa & 0xFFFFFF) >> -(exp2 + 1);
 }
 p = outbuf;

 if (x.L < 0)
 {
  *p++ = '-';
 }
 if (int_part == 0)
 {
  *p++ = '0';
 }
 else
 {
  ltoa(p, int_part, 10);
  while (*p)
   p++;
 }
 *p++ = '.';

 if (frac_part == 0)
  *p++ = '0';
 else
 {
  char m, max;

  max = sizeof (outbuf) - (p - outbuf) - 1;
  if (max > 7)
  {
   max = 7;
  }

  /* print BCD */
  for (m = 0; m < max; m++)
  {
   /* frac_part *= 10; */
   frac_part = (frac_part << 3) + (frac_part << 1);

   *p++ = (frac_part >> 24) + '0';
   frac_part &= 0xFFFFFF;
  }
  /* delete ending zeroes */
  for (--p; p[0] == '0' && p[-1] != '.'; --p)
   ;
  ++p;
 }
 *p = 0;

 return outbuf;
}

Posted by 셈말짓기 :

// TestSprintF.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"

int sprintf_with_args (char* buf, char* format, void** args)
{  
 char* start;  

 char  field_format[32];
 char* field;
 char* field_type;

 int   result;


 start = buf;

 while( *format )  
 {  
  if( *format != '%' )
  {  
   *buf++ = *format++;  
   continue;  
  }

  field      = field_format;
  field_type = 0;

  *field++ = *format++;
  while( *format && !field_type && field<field_format+32)
  {
   switch (*format)
   {
   case '%':
   case 'c'://int
   case 'C':
   case 'd':
   case 'i':
   case 'o':
   case 'u':
   case 'x':
   case 'X':
   case 'e':
   case 'E'://double
   case 'f':
   case 'g':
   case 'G':
   case 'a':
   case 'A':
   case 'n'://int*
   case 'p'://void*
   case 's'://char*
   case 'S'://wchar_t*
    field_type = format;
    break;
   }
   *field++ = *format++;
  }

  if (field_type)
  {
   *field = 0;
#pragma warning( push )
#pragma warning( disable: 4996 )
   switch (*field_type)
   {
   case '%':
    *buf++ = '%'; 
    break;

   case 'c'://int
   case 'C':
   case 'd':
   case 'i':
   case 'o':
   case 'u':
   case 'x':
   case 'X':
    result = sprintf (buf, field_format, *((int*)(*args)));
    if (result>0)
    {
     buf+=result;
    }
    else
    {
     return -1;
    }
    args++;
    break;
   case 'e':
   case 'E'://double
   case 'f':
   case 'g':
   case 'G':
   case 'a':
   case 'A':
    result = sprintf (buf, field_format, *((double*)(*args)));
    if (result>0)
    {
     buf+=result;
    }
    else
    {
     return -1;
    }
    args++;
    break;
   case 'n'://int*
   case 'p'://void*
   case 's'://char*
   case 'S'://wchar_t*
    result = sprintf (buf, field_format, *((int**)(*args)));
    if (result>0)
    {
     buf+=result;
    }
    else
    {
     return -1;
    }
    args++;
    break;
   }
  }
#pragma warning( pop )
 }
 *buf = '\0';   

 return (int)(buf-start); 

 return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char*  pFormatString = "문자열%%[%d][%d][%5d] [%s] [%x] [%e][%.03f]메%q세지 \r\n";
 char   szMessage[256];
 void*  pParameters[7];
 int    Parameters[32];
 char   param1 = 100;
 short  param2 = 101;
 int    param3 = 102;
 char*  param4 = "xxx";
 int    param5 = -1;
 double param6 = 0.1;
 double param7 = 0.5;

 Parameters[0] = (int)param1;
 Parameters[1] = (int)param2;
 Parameters[2] = (int)param3;
 Parameters[3] = (int)param4;
 Parameters[4] = (int)param5;
 memcpy (&Parameters[5], &param6, sizeof(double));
 memcpy (&Parameters[7], &param7, sizeof(double));

#if 0
 pParameters[0] = &Parameters[0];
 pParameters[1] = &Parameters[1];
 pParameters[2] = &Parameters[2];
 pParameters[3] = &Parameters[3];
 pParameters[4] = &Parameters[4];
 pParameters[5] = &Parameters[5];
 pParameters[6] = &Parameters[7];
#else
 pParameters[0] = &param1;
 pParameters[1] = &param2;
 pParameters[2] = &param3;
 pParameters[3] = &param4;
 pParameters[4] = &param5;
 pParameters[5] = &param6;
 pParameters[6] = &param7;
#endif

 sprintf_with_args (szMessage, pFormatString, pParameters);
 printf (szMessage);

 return 0;
}


 

Posted by 셈말짓기 :

#include  <stdio.h>
#include  <signal.h>
#include  <setjmp.h>

jmp_buf  g_my_jump_buffer;

bool try_signal (int sig)
{
    int result;

    result = setjmp(my_jump_buffer, sig);
    printf ("setjmp(): resutl %d \r\n", result);
    if (sig==result)
        return true;
    return false;
}

void signal_handler (int sig)
{
    printf ("signal_handler(%d) \r\n", sig);
    longjmp (g_my_jump_buffer, sig);
}

int main (void)
{
    unsigned int* p = (unsigned int*)0xffffffff;

    signal (SIGBUS, signal_handler);

    while (1)
    {    
        if (try_signal (SIGBUS)==0)
        {
            printf ("no signal \r\n");
            *p = 0x00000001;
        }
        else
        {
            printf ("signal \r\n");
        }
    }
    return 0;
}

이런식으로 setjmp를 사용하면 프로그램이 망한다.
setjmp시 현재 스택 포인터를 저장하는 역할을 하기 때문에 위에 처럼 setjmp를 랩핑해서 함수를 호출하여 사용하면
1. 위에 main함수에서 try_signal()을 호출하고 
2. signal이 발생되어서 signal_handler()를 거쳐서
3. 다시 setjmp()함수 위치로 복귀하려 했을때 
   이전 try_signal()이 호출 되어서 저장했던 스택포인터는 
   이전 try_singal()가 main()함수로 복귀를 했으므로 저장했던 해당 스택포인터가 유효 하지 않다.
랩핑해서 사용하고 싶을땐 아래와 같이 inline함수로 구현하던가 매크로로 구현해야한다.

#include  <stdio.h>
#include  <signal.h>
#include  <setjmp.h>

jmp_buf  g_my_jump_buffer;

inline bool try_signal (int sig)
{
    int result;

    result = setjmp(my_jump_buffer, sig);
    printf ("setjmp(): resutl %d \r\n", result);
    if (sig==result)
        return true;
    return false;
}

void signal_handler (int sig)
{
    printf ("signal_handler(%d) \r\n", sig);
    longjmp (g_my_jump_buffer, sig);
}

int main (void)
{
    unsigned int* p = (unsigned int*)0xffffffff;

    signal (SIGBUS, signal_handler);

    while (1)
    {    
        if (try_signal (SIGBUS)==0)
        {
            printf ("no signal \r\n");
            *p = 0x00000001;
        }
        else
        {
            printf ("signal \r\n");
        }
    }
    return 0;
}

Posted by 셈말짓기 :

/////////////////////////////////////////////////////////////////////////////
//===========================================================================
template<typename T>
class Singleton : public T
{
protected:
 Singleton();

public:
 static Singleton<T>& Instance(void);
};

//===========================================================================
template<typename T>
Singleton<T>::Singleton ()
{
}

template<typename T>
Singleton<T>& Singleton<T>::Instance(void)
{
 static Singleton<T> single_instance;

 return single_instance;
}

/////////////////////////////////////////////////////////////////////////////
//===========================================================================
class TestTaskData
{
...
};

/////////////////////////////////////////////////////////////////////////////
//===========================================================================
template class Singleton<TestTaskData>;

명시적으로 템플릿 클래스의 오브젝트 코드를 생성하기 위해서는(Explicit template instantiation)
위의 코드를 cpp에 추가 하면 해당 cpp의 오브젝트 파일에 생성된다.

참고사항> 
#  gcc에서 컴파일 옵션 template instantiation 
   -fimplicit-templates : 묵시적 템플릿 인스턴티에이션을 사용 (템플릿 클래스의 인라인화)
   -fno-implicit-templates : 묵시적 템플릿 인스턴티에이션을 사용 안함
   -frepo : rpo 파일을 통해서 템플릿 인스턴스 db를 생성해서 자동으로 처리

여담>
1. STL 쓰면서 -fno-implicit-templates 옵션 사용하면 죽음이다.
2. msvc++ 생각보다 똑똑한 녀석이었다. ~_~;
3. #pragma interface 와 implementation 살펴보자.

Posted by 셈말짓기 :

# 일반 Class 형
class Data_Class
{
public:
 int value1;
 int value2;
 int value3;

public:
 Data_Class ();
 Data_Class (const Data_Class& o);
 Data_Class& operator=(const Data_Class& rhs);
};

Data_Class::Data_Class ()
{
 value1=0;
 value2=0;
 value3=0;
}

Data_Class::Data_Class (const Data_Class& o)
{
 value1=o.value1;
 value2=o.value2;
 value3=o.value3;
}

Data_Class& Data_Class::operator=(const Data_Class& rhs)
{
 value1=rhs.value1;
 value2=rhs.value2;
 value3=rhs.value3;

 return *this;
}

# Inline Class 형
class Data_Inline_Class
{
public:
 int value1;
 int value2;
 int value3;

public:
 Data_Inline_Class ()
 {
  value1=0;
  value2=0;
  value3=0;
 }


 Data_Inline_Class (const Data_Inline_Class& o)
 {
  value1=o.value1;
  value2=o.value2;
  value3=o.value3;
 }

 Data_Inline_Class& operator=(const Data_Inline_Class& rhs)
 {
  value1=rhs.value1;
  value2=rhs.value2;
  value3=rhs.value3;

  return *this;
 }
};

Posted by 셈말짓기 :

심각하게 공감간다..

2009. 12. 30. 17:05 from 낙서판

Posted by 셈말짓기 :

GetRemovableDrives()

2009. 11. 27. 14:09 from 셈말짓기/Windows


 void GetRemovableDrives (std::vector<std::wstring>& logicalDrives)
 {
  TCHAR  buf[512];
  TCHAR* rootPathName = buf;
  BOOL   hasVolumeInfo;
  UINT   driveType;


  if (0==GetLogicalDriveStrings (512-1, buf))
   return;

  do
  {
   driveType     = GetDriveType (rootPathName);
   hasVolumeInfo = GetVolumeInformation (rootPathName,
              NULL, 0,
              NULL, NULL, NULL,
              NULL, 0);
   if (driveType==DRIVE_REMOVABLE && hasVolumeInfo==TRUE)
   {
    logicalDrives.push_back (std::wstring (rootPathName) );
   }
   while (*rootPathName++);
  } while (*rootPathName);
 }

Posted by 셈말짓기 :

USE [zm]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/** zm_marine_farm
 **/
CREATE PROCEDURE [dbo].[zm_add_gathering_data] (
 @param1 NVARCHAR(32),
 @param2 NVARCHAR(32),
 @param3 FLOAT,
 @param4 FLOAT,
 @param5 FLOAT
) AS
BEGIN
 IF  (SELECT COUNT(TABLE_NAME)  
       FROM INFORMATION_SCHEMA.TABLES  
       WHERE
INFORMATION_SCHEMA.TABLES.TABLE_NAME=@param1) = 0
 BEGIN
  EXEC('CREATE TABLE [dbo].[' + @param1 + '] (
    [gather_time]       [datetime]     NOT NULL,
    [device_node_id]    [nvarchar](16) NOT NULL,
    [water_temperature] [float]        NULL,
    [demand_oxygens]    [float]        NULL,
    [salinity]          [float]        NULL)')
 END

 EXEC('INSERT INTO [dbo].[' + @param1 + '] (
                      [gather_time]      ,
                      [device_node_id]   ,
                      [water_temperature],
                      [demand_oxygens]   ,
                      [salinity]         )
              VALUES (GETDATE(), '''
                      + @param2 + ''','
                      + @param3 + ','
                      + @param4 + ','
                      + @param5 + ')' )
END

Posted by 셈말짓기 :