달력

52024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

Linux version

Lang, Tool, Env 2016. 2. 15. 03:10

 

 

v4.4 Date: Sun Jan 10 15:01:32 2016 -0800

v4.3 Date: Sun Nov 1 16:05:25 2015 -0800

v4.2 Date: Sun Aug 30 11:34:09 2015 -0700

v4.1 Date: Sun Jun 21 22:05:43 2015 -0700

v4.0 Date: Sun Apr 12 15:12:50 2015 -0700

v3.19 Date: Sun Feb 8 18:54:22 2015 -0800

v3.18 Date: Sun Dec 7 14:21:05 2014 -0800

v3.17 Date: Sun Oct 5 12:23:04 2014 -0700

v3.16 Date: Sun Aug 3 15:25:02 2014 -0700

v3.15 Date: Sun Jun 8 11:19:54 2014 -0700

v3.14 Date: Sun Mar 30 20:40:15 2014 -0700

v3.13 Date: Sun Jan 19 18:40:07 2014 -0800

v3.12 Date: Sun Nov 3 15:41:51 2013 -0800

v3.11 Date: Mon Sep 2 13:46:10 2013 -0700

v3.10 Date: Sun Jun 30 15:13:29 2013 -0700

v3.9 Date: Sun Apr 28 17:36:01 2013 -0700

v3.8 Date: Mon Feb 18 15:58:34 2013 -0800

v3.7 Date: Mon Dec 10 19:30:57 2012 -0800

v3.6 Date: Sun Sep 30 16:47:46 2012 -0700

v3.5 Date: Sat Jul 21 13:58:29 2012 -0700

v3.4 Date: Sun May 20 15:29:13 2012 -0700

v3.3 Date: Sun Mar 18 16:15:34 2012 -0700

v3.2 Date: Wed Jan 4 15:55:44 2012 -0800

v3.1 Date: Mon Oct 24 09:10:05 2011 +0200

v3.0 Date: Thu Jul 21 19:17:23 2011 -0700

v2.6.39 Date: Wed May 18 21:06:34 2011 -0700

v2.6.38 Date: Mon Mar 14 18:20:32 2011 -0700

v2.6.37 Date: Tue Jan 4 16:50:19 2011 -0800

v2.6.36 Date: Wed Oct 20 13:30:22 2010 -0700

v2.6.35 Date: Sun Aug 1 15:11:14 2010 -0700

v2.6.34 Date: Sun May 16 14:17:36 2010 -0700

v2.6.33 Date: Wed Feb 24 10:52:17 2010 -0800

v2.6.32 Date: Wed Dec 2 19:51:21 2009 -0800

v2.6.31 Date: Wed Sep 9 15:13:59 2009 -0700

v2.6.30 Date: Tue Jun 9 20:05:27 2009 -0700

v2.6.29 Date: Mon Mar 23 16:12:14 2009 -0700

v2.6.28 Date: Wed Dec 24 15:26:37 2008 -0800

v2.6.27 Date: Thu Oct 9 15:13:53 2008 -0700

v2.6.26 Date: Sun Jul 13 14:51:29 2008 -0700

v2.6.25 Date: Wed Apr 16 19:49:44 2008 -0700

v2.6.24 Date: Thu Jan 24 14:58:37 2008 -0800

v2.6.23 Date: Tue Oct 9 13:31:38 2007 -0700

v2.6.22 Date: Sun Jul 8 16:32:17 2007 -0700

v2.6.21 Date: Wed Apr 25 20:08:32 2007 -0700

v2.6.20 Date: Sun Feb 4 10:44:54 2007 -0800

v2.6.19 Date: Wed Nov 29 13:57:37 2006 -0800

v2.6.18 Date: Tue Sep 19 20:42:06 2006 -0700

v2.6.17 Date: Sat Jun 17 18:49:35 2006 -0700

v2.6.16 Date: Sun Mar 19 21:53:29 2006 -0800

v2.6.15 Date: Mon Jan 2 19:21:10 2006 -0800

v2.6.14 Date: Thu Oct 27 17:02:08 2005 -0700

v2.6.13 Date: Sun Aug 28 16:41:01 2005 -0700

v2.6.12 Date: Fri Jun 17 12:48:29 2005 -0700

v2.6.11

'Lang, Tool, Env' 카테고리의 다른 글

Ubuntu /home 옮기기  (0) 2012.08.04
struct 내 flag용으로 쓸 1bit 크기 변수 사용하기  (0) 2010.05.09
struct timeval & long long  (0) 2010.03.31
IEEE Floating-Point Format  (1) 2009.09.13
chroot  (0) 2008.04.06
Posted by neodelicious
|

사정상 VBOX 에 Ubuntu 를 설치해서 사용하고 있는데,
기존에 사용하던 /home 이 HDD(SSD) 용량을 거의 다 차지하고 말았다.

Android 같은 대용량 Source 를 받고 Build 하면 금새 몇 십 GB 를 소모하는데

,
그리고 VBOX 초기 설정시 HDD 크기를 너무 작게 설정했기 때문이다.
사실 http://virtualboxes.org/images/ubuntu/ 에서 이미 Ubuntu 를 설치한 VBOX image 를 이용하면 기본 8GB 로 설정되어 있어서 금새 부족해진다.

생각해보면 /home 전용 VBOX image 를 별도로 관리하면, 이후에 VBOX master HDD image 에 문제가 생겨도 손쉽게 복구할 수 있을 것 같아서 HHD 를 추가하고 /home 을 분리하는 방법을 찾아봤다.

이미 같은 필요를 느끼는 사람이 많아서인지 ubuntu help page에 잘 설명되어 있었다.
https://help.ubuntu.com/community/Partitioning/Home/Moving

방법은 우선 VBOX 에서 HDD 를 적당히 크게 하나를 추가하고 Ubuntu 에서 format 한다.
그리고 위 ubuntu help page 처럼 /home 을 복사하고 mount point 를 변경한다.

ubuntu help page 방법의 command 만 복사하면 아래와 같다.

1. 실행후 새 HDD 의 UUID 확인
$ sudo blkid

2. fstab backup 후 fstab 임시 수정 (UUID는 1. 에서 확인한 값으로 변경, option 도 필요하면 수정)
$ sudo cp /etc/fstab /etc/fstab.$(date +%Y-%m-%d)
$ gksu gedit /etc/fstab
UUID=????????   /media/home    ext4          nodev,nosuid       0       2

3. 새 HDD mount
$ sudo mkdir /media/home
$ sudo mount -a

4. /home 복사 (참고 - .gvfs 를 복사 못 해도 warning message 출력 금지)
$ sudo rsync -aXS --exclude='/*/.gvfs' /home/. /media/home/.
$ sudo diff -r /home /media/home

5. fstab 재 수정(/home 으로 변경), /home 변경 및 재부팅
$ gksu gedit /etc/fstab
UUID=???????? /home ext4 nodev,nosuid 0 2
$ cd / && sudo mv /home /old_home && cd / && sudo mkdir -p /home
$ sudo reboot

6. 이전 /home 삭제
$ sudo rm -r /old_home

'Lang, Tool, Env' 카테고리의 다른 글

Linux version  (0) 2016.02.15
struct 내 flag용으로 쓸 1bit 크기 변수 사용하기  (0) 2010.05.09
struct timeval & long long  (0) 2010.03.31
IEEE Floating-Point Format  (1) 2009.09.13
chroot  (0) 2008.04.06
Posted by neodelicious
|
프로그램을 짜다 보면 flag용으로만 사용하여 실제로는 1byte는 커녕 1bit만 할당해도 사용하는데 충분한 경우가 있다. 이때 bit 단위로 실제 사용 크기만큼만 할당해서 사용하면 메모리를 아낄 뿐 아니라 해당 변수를 복사할 때 빠를 것으로 생각된다.

물론 함수 내에서 잠깐 사용할 경우에는 int 로 선언해도 무방하고, 다른 모든 곳에서도 int 혹은 char 등으로 선언해도 사용하는데도 된다.

그러니까 아마도 주로 사용하는 struct 내에  Bool과 같이 단순 flag만으로 사용하는 변수가 많을 경우 유용할 것이다.

사용 방법은 간단한다.
변수 뒤에 ' : 크기' 와 같은 방식으로 bit 크기를 설정하면 되며, 주의할 것은 unsigned 를 붙여야 한다는 것이다.
예를 들어 unsigned char a1 : 1; 는 1 bit 크기를 할당한다.

관련해서 테스트 소스를 아래와 같이 작성했다.

#include <stdio.h>

struct Mystr {
 unsigned char a1 : 4;
 unsigned char a2 : 2;
 unsigned char a3 : 1;
};

int main(int argc, char *argv[])
{
 int i;
 struct Mystr mystr = { .a3=1, };

 printf("sizeof(struct Mystr) is %d\n", sizeof(struct Mystr));
 if (mystr.a3 == 1)
  printf(".a3=1 works!\n");

 return 0;
}
그 결과는 다음과 같다.
참고적으로 struct Mystr내 bit 크기가 8보다 큰 9라면 sizeof() 결과는 2가 된다.
그리고 unsigned char가 아닌 char 를 쓰면 '1'이 아닌 '0xFFFF'와 같은 값이 저장되어 문제가 된다.
sizeof(struct Mystr) is 1
.a3=1 works!

'Lang, Tool, Env' 카테고리의 다른 글

Linux version  (0) 2016.02.15
Ubuntu /home 옮기기  (0) 2012.08.04
struct timeval & long long  (0) 2010.03.31
IEEE Floating-Point Format  (1) 2009.09.13
chroot  (0) 2008.04.06
Posted by neodelicious
|
현재 시각을 측정하는 손쉬운 방법은 gettimeofday()를 이용하는 것으로,
이때 struct timeval 구조체를 이용하게 된다.

<API>
int gettimeofday(struct timeval *tv, struct timezone *tz);

<example>
struct timeval tv;
if (!gettimeofday(&tv, NULL)) fprintf(stderr, "%s error at %d\n", __FUNCTION__, __LINE__);


그리고 /usr/include/sys/time.h 파일을 보면 다음과 같은 편리한 macro를 제공함을 알 수 있다.
__USE_BSD 가 언제 #define 되는지 모르겟지만 이용 할 수 있었다.
stuct timeval 에 sec 부분과 usec 부분으로 분리되어 있는데 아래 3개 macro는 유용할 것이다.
timercmp(a, b, CMP)
timeradd(a, b, result)
timersub(a, b, result)
예를 들어 현재 시각을 매번 측정하여 그 차이를 위의 timersub를 통해 손쉽게 계산할 수 있고,
그 차이를 timeradd를 통해 손쉽게 계속 더해갈 수 있다.

#ifdef __USE_BSD
/* Convenience macros for operations on timevals.
   NOTE: `timercmp' does not work for >= or <=.  */
# define timerisset(tvp)        ((tvp)->tv_sec || (tvp)->tv_usec)
# define timerclear(tvp)        ((tvp)->tv_sec = (tvp)->tv_usec = 0)
# define timercmp(a, b, CMP)                                                  \
  (((a)->tv_sec == (b)->tv_sec) ?                                             \
   ((a)->tv_usec CMP (b)->tv_usec) :                                          \
   ((a)->tv_sec CMP (b)->tv_sec))
# define timeradd(a, b, result)                                               \
  do {                                                                        \
    (result)->tv_sec = (a)->tv_sec + (b)->tv_sec;                             \
    (result)->tv_usec = (a)->tv_usec + (b)->tv_usec;                          \
    if ((result)->tv_usec >= 1000000)                                         \
      {                                                                       \
        ++(result)->tv_sec;                                                   \
        (result)->tv_usec -= 1000000;                                         \
      }                                                                       \
  } while (0)
# define timersub(a, b, result)                                               \
  do {                                                                        \
    (result)->tv_sec = (a)->tv_sec - (b)->tv_sec;                             \
    (result)->tv_usec = (a)->tv_usec - (b)->tv_usec;                          \
    if ((result)->tv_usec < 0) {                                              \
      --(result)->tv_sec;                                                     \
      (result)->tv_usec += 1000000;                                           \
    }                                                                         \
  } while (0)
#endif  /* BSD */

그런데 struct timeval 을 그대로 이용할 때는 불편할 때가 있다.
예를 들어 sec을 일부와 usec의 일부만을 출력하거나
다른 일반 int type으로 저장한 시간과 비교할 때가 그럴 수 있을 것이다.

(어디까지나 선택사항이지만) 이때는 struct timeval 을 long long 으로 변환해서 저장하는 것이 편하다.
아래와 같이 long long time 에 저장하는 것이다.
time = tv.tv_sec * 1000000LL + tv.tv_usec;

참고적으로 혹시 전환 과정에서 data 손실을 우려할 수 있으나 그렇지 않다.
long long type이 보통 8byte 이고, struct timeval의 tv_sec 과 tv_usec 이 각각 4byte 인데,
실제로는 tv_usec의 값은 최대 10^6 - 1 로서, 이는 2진수 값으로 20bit 이하이다.
따라서 20bit 인 2.5byte를 shift 하더라도 데이터 손실이 없는 것이다.

아래는 관련해서 테스트한 소스 코드이며,
struct timeval : 1270047284.534099
long long      : 1270047284534099
실행결과 바로 위와 같이 두 값이 같음을 알 수 있다.

#include <stdio.h>
#include <sys/time.h>

int main(int argc, char *argv[])
{
        struct timeval tv;
        long long time;

        if (gettimeofday(&tv, NULL)) fprintf(stderr, "%s error at %d\n", __FUNCTION__, __LINE__);
        time = tv.tv_sec * 1000000LL + tv.tv_usec;

        printf("struct timeval : %d.%-6d\n", (int)tv.tv_sec, (int)tv.tv_usec);
        printf("long long      : %lld\n", time);

        return 0;
}

'Lang, Tool, Env' 카테고리의 다른 글

Ubuntu /home 옮기기  (0) 2012.08.04
struct 내 flag용으로 쓸 1bit 크기 변수 사용하기  (0) 2010.05.09
IEEE Floating-Point Format  (1) 2009.09.13
chroot  (0) 2008.04.06
임베디드 기초 교육 정리  (0) 2007.08.26
Posted by neodelicious
|
어쩌다보니 Float 변수 값의 구조를 알아야 할 필요가 생겼다.
그래서 관련해서 프로그램도 짜 보고 인터넷도 찾아보고 그 결과를 여기에 정리한다.

1. IEEE Floating-Point Format

우선 Float Format이 어떻게 되어 있는지 알아야 한다.
HP 링크에서 발췌한 다음 Format을 보자.


여기서 s는 sign 값이고, exp 값에서 127을 뺀 값이 2진수 값으로 처음 '1' 이 있는 위치이다.
그리고 그 처음 '1' 이후의 값들이 mantissa의 값이다.


2. 분석 예제

아래와 같이 일부 값에 대한 Floating 값을 분석해 보자.

알다시피 10진 정수 부분은 2진수로 계산하여 표현하기가 싶다.
하지만 소수 부분을 2진수로 표현하려면 2로 나누는 것이 아니라 2를 곱해가며 그 값을 확인해야 한다.
참고적으로 하다보면 2를 곱하다보니 2, 4, 8, 6 (1001)이 반복되는 경우가 쉽사리 발생함을 확인할 수 있다.
여하튼 계산 방법은 링크를 참조하고 실제로 계산하면 다음과 같다.

0.1 -> 0b     0001 1001 1001 1001
0.6 -> 0b     1001 1001 1001 1001
2.3 -> 0b 10 0 1001 1001 1001

1001 반복함을 보이고자 일부러 1001를 하나의 묶음으로 구분해보았다.

사실 여기에서 중요한 것은 반복이 아니라
정수 부분이 있는 경우와 없는 경우 모두에 대해서
소수 부분과 같이 일렬로 나열 했을 때 첫 번째 1이 몇 번째 있는 가이다.

위에서 0.1과 0.6은 첫 번째 '1'이 각각 4 번째, 1 번째에 있다.
그런데 이는 소수에 대해서이므로 실제로는 각각 -4 번째, -1 번째가 된다.
그리고 2.3의 경우 처음 10은 정수 부분 2를 나타내는 것으로 처음 '1'이 2 번째가 된다.
즉, 2.3의 값에 대해서 처음 2개 숫자는 정수 부분이고 나머지는 소수 부분이다.

그렇다면 실제 Float Format에서는 어떻게 저장될까?
위에서 이미 살짝 언급했지만,
처음 '1'이 있는 위치값에 +127을 해서 exp에 저장하고,
처음 '1'을 제외한 나머지 값을 mantissa에 저장한다.

따라서 위의 값에 대해서 mantissa 값은 다음과 같다.

0.1 -> 0b     (0001 제외) 1001 1001 1001
0.6 -> 0b     (1 제외) 001 1001 1001 1001
2.3 -> 0b (1 제외) 0 0 1001 1001 1001


3. Test Program

위의 이론을 확인하기 위해서 C 언어 테스트 프로그램을 작성해서 확인했다.
실제 코드와 몇 가지 값에 대한 결과를 첨부한다.

처음에 char*로 하나씩 읽었는데 값이 32bit float 값의 하위 8bit 부터 읽어졌는데,
아래 주소의 소스를 보고 틀렸음을 확인했다.
http://hisjournal.net/blog/160
더 나아가 위의 주소 소스의 해당 부분을 거의 그대로 이용하여 bit 단위로 표현하였을 밝힌다.


플래쉬 버전 업 이후로 테터툴즈와 버전 문제라고 하는데
여튼 업로드가 안 되어서 임시적으로 직접 올리고 링크한다.
--> 소스 파일 : main.c
--> 결과 파일 : float.JPG


참고자료 정리
1. HP 웹페이지 상의 IEEE Floating-Point Format
  http://docs.hp.com/en/B3901-90003/ch10s03.html
2. 소수점이 있는 실수(정수) 진수 변환 연습
  http://math88.com.ne.kr/crypto/isan/2jinbup.html
3. Float 엿보기
  http://hisjournal.net/blog/160
Posted by neodelicious
|

chroot

Lang, Tool, Env 2008. 4. 6. 10:32

chroot [dir path]
를 통해 현재 root (/)가 아닌 다른 임의의 폴더를 root (/) 로 설정할 수 있다.

http://www.joinc.co.kr/modules/moniwiki/wiki.php/man/2/chroot
Posted by neodelicious
|

*** printf() options

%hd - half decimal, 즉 short
%f - float와 double
%lf - long double
%5d - 우측 정렬, 빈칸 삽입
%+5d - 부호 표기
%-5d - 좌측 표기
%05d - 우측 표기, 좌측에 숫자'0' 삽입
%.2f - 소수점 이하 출력할 숫자의 개수 제한

0x%x 대신에 %p를 쓰면 자동으로 0x를 붙여준다.
주소 출력시 %p를 이용해 보자.

******************************************

*** 정수형과 실수형의 기본 자료형은 각각 int와 double이다.

따라서 int x = 10 에서는 형변형이 없지만
float y = 10.1 에서는 10.1을 double형으로 인식하여 이를 float로 자동 형변환 한다.

또한 다음의 경우 Error가 아니다.
static a[3];
이는 type을 안 써서 기본형인 int으로 인식하기 때문이다.

*** 기본 함수형태는 int FuncName (void) 이다.

따라서 int f1 (void) 의 경우 호출 전에 선언하지 않아도 인지한다.

******************************************

*** int main ( int argc, char * argc[], char * envp[] )

배열 envp 안에 환경 정보가 저장되어 있다.
이 배열의 마지막은 NULL이다.

******************************************

*** char * strdup (const char *)

입력 string의 메모리를 복사하는데, 또 다른 동적 메모리를 할당하여 복사한다.
추후 메모리 반환을 해줘야 한다.

******************************************

*** 지역변수를 stack에 저장할 때 I/O 크기에 따라 자동으로 메모리 공간을 일부러 띄운다.

char 형, short 형 변수를 각각 선언하면 stack의 높은 주소의 위치부터 차례로 이용하는데,
char 가 1byte이고 short가 2byte일 때 다음과 같은 경우가 될 수 있다.

예1)
8F - char
8E - 없음
8D - short 상위
8C - short 하위

예2) - visual C++ 6.0 실험 결과
8F - 없음
8E - 없음
8D - 없음
8C - char
8B - 없음
8A - 없음
89 - short 상위
88 - short 하위

******************************************

*** prompt 상에서 editor 실행

gedit &
-> gedit text editor 실행
kate &
-> gedit와 다른 text editor

******************************************

*** PC에서 vmware 상의 linux와 기본 OS인 winXP 사이의 ftp 파일 전송 방법
*** 주의 !!! 일부 설정 방법이 생략되어 있음

service vsftpd start
-> linux 內 ftp 서버 활성화

winXP에서 vmware 상이 linux의 IP에 대해서 ftp 연결 시도
ftp [Linux IP]
get, put 혹은 mget, mput 이용 파일 전송

******************************************

*** 틀리기 쉬운 C 문법

#define FLAG  0x02 일때
flag 변수의 bit 2가 set인지 확인하고자 한다면,
if (flag & FLAG) 를 써야 하는데,
if (flag & FLAG != 0) 로 쓰면 != 가 & 보다 우선하므로 틀린다.

val = high << 4 + low;
에서 high를 상위로 하고 low를 하위로 하는 것처럼 오인할 수 있는데,
산술연산자 + 가 먼저 실행되어 잘못된 계산을 하게 된다.

== 은 < , > 보다 우선 순위가 낮아서
n1 > n2 == n2 > n3
의 경우 == 가 나중에 되므로 주의한다.

치환연산자는 관계연산자보다 우선순위가 낮다. (사실 치환연산자는 제일 낮다.)
while ( c = getchar() != '\n' )
에서 != 를 먼저하므로 error이다.


******************************************

*** code 상에 정의되지 않은 값을 compile할 때 정의하는 방법

opPriorErr.C 파일을 cc를 이용하여 compile할 때,
'CASE' 라는 값을 '1'로 설정하려면
다음과 같이 '-D' 이후에 'CASE'를 입력한다.

cc -DCASE=1 opPriorErr.C

'Lang, Tool, Env' 카테고리의 다른 글

IEEE Floating-Point Format  (1) 2009.09.13
chroot  (0) 2008.04.06
[cpp] fstream::getline() 쓸 때 clear()를 꼭 쓰자  (0) 2007.08.04
C 프로그래머가 알아야 할 것들  (1) 2007.05.16
CRC를 통한 error 검출  (0) 2007.05.16
Posted by neodelicious
|

열심히 코딩을 잔뜩 한 후에 컴파일 하고 나서 알 수 없는 결과에 당혹해 하다가,
디버깅 모드에서 추적한 끝에 getline()함수가 말썽인을 것을 알았다.

결론적으로 getline()함수를 이용할 경우,
한  번 이용한 다음에 다시 getline()함수를 이용하기 전에 clear()함수를 호출하는 것이 좋다.
그렇지 않을 경우 두 번째 호출한 getline()함수는 buffer에 "" 즉,  '\0'만을 저장한다.

왜 그런지 알아보기 위해서 getline()에 대해서 참고 페이지를 읽어보고
fail()과 bad()으로 failbit이나 badbit가 set되어 있는지 테스트 해 보았다.
bad()에서는 clear되어 있고 fail()에서는 set되어 있는 것으로 봐서는 failbit가 set되어 있는 것이었다.
그리고 아래는 getline()에 대해서 참고자료에서 알려준 failbit에 대한 설명 중 일부이다.
failbit - This is also set if the function stops extracting
             because n-1 characters were extracted

그러니까 한 마디로 말 해서 꽉 차게 읽으면 failbit가 발생한다는 것이다.

그리고 참고자료에 getline()에 대한 설명으로 아래와 같은 글이 있었다.
The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation.
그러니까 입력 과정 중에 에러가 나도 멈춘다는 것이다.

여하튼 buffer가 꽉 찰 것을 예상한 다면 clear()를 통해 두 번째 getline() 이후에는
error control stategoodbit 로 만들어 줘야 한다.
이는 file stream 뿐만 아니라 일반 키보드 입력 stream에서도 마찬가지이다.
아무튼 getline() 쓰고 buffer에서 읽었는데, 꽉 차면 다음 번엔 꽝이닷~

직접 참고 페이지에서 정보를 얻기 바란다.
fsream 참고 - http://www.cplusplus.com/reference/iostream/fstream/
istream::getline 참고 - http://www.cplusplus.com/reference/iostream/istream/getline.html
ios:clear() 참고  - http://www.cplusplus.com/reference/iostream/ios/clear.html

아래 코드는 이를 테스트 해보기 위해서 짠 코드이다.
ttt.txt 라는 파일을 열어서 제대로 열렸다면,
파일 끝까지 10bytes씩 읽어온다.

#include <iostream>
#include <fstream>
using namespace std;

#define MAX_BUF_SIZE 10

int main()
{
fstream fp;

fp.open("ttt.txt");    // fp.open("ttt.txt", fstream::in);  
char szBuffer[MAX_BUF_SIZE];
if (fp.is_open()) {  
do {
  fp.clear();
  fp.getline(szBuffer, MAX_BUF_SIZE);
}while(fp.gcount() == MAX_BUF_SIZE - 1);
}

fp.close();
return 0;
}

'Lang, Tool, Env' 카테고리의 다른 글

chroot  (0) 2008.04.06
임베디드 기초 교육 정리  (0) 2007.08.26
C 프로그래머가 알아야 할 것들  (1) 2007.05.16
CRC를 통한 error 검출  (0) 2007.05.16
do while(0) 을 이용한 goto 대체  (0) 2007.05.16
Posted by neodelicious
|
검색하다보니 아래 싸이트를 찾을 수 있었다.

http://klausler.com/cnotes.txt


좋은 정보라고 생각한다.
개인 홈페이지 내 파일 같은데 링크가 사라질까봐 무단으로 복사해서 덧붙인다.
Peter Klausler 님.... 감사합니다 ^^;;




Some things every C programmer should know about C
PMK 10-16-2002


Types
-----

Every constant, object, function, and expression in C has a type.
Most generally, a type is either an unqualified type or such a type
qualified with "const", "volatile", or both qualifiers.  Unqualified
types comprise three categories:

	Object types
		Scalar
		   Arithmetic
		      Integral
		         signed/unsigned/plain
		            character types
		            short, int, long
		         bitfield
		         enumeration
		      Floating-point
		   Pointer to general type
		Aggregate
		   struct/union of object types and bitfields
		   known-size array of objects
	Incomplete types
		void
		undefined struct/union
		array of unknown size of objects
		array of incomplete type (except void)
	Function returning void or unqualified object type (except array)
		(with no arguments, with unknown or old-style arguments, or
		 with prototyped arguments of general types)

Bitfields may appear only as struct/union members, so
there are no pointers to bitfields, arrays of bitfields, or
functions taking or returning bitfields.

Some types are silently replaced.  A qualified array type becomes
an unqualified array of the qualified type, and function arguments
that are arrays or functions become pointers.


Declarator Syntax
-----------------

Binding is just like expressions: postfix before prefix.  So
parentheses are necessary in declarators only for function arguments
and for pointers to functions and arrays!

In qualified pointer types, the pointer qualifiers appear after the *.

How to easily read a declaration from left to right:
	transform function argument types from inside out first
	move the base type to the end
	add outer parentheses if there's an initial *
	change every (*...) to ... ->
		one -> for each *
		move qualifiers, so * const becomes const ->

Example: const int *(**const x [])()

	*(**const x [])() const int		base type to end
	(*(**const x [])()) const int		add outer parens
	(**const x [])() -> const int		remove outer ()
	x [] const -> -> () -> const int	remove inner ()

	array of constant pointers to pointers to functions
	returning pointers to constant ints


Types of Constants
------------------

Floating-point constants are "double" unless suffixed by 'F' or 'L'.

Integer constants take the first type that fits in one of these lists:
	with 'U':	unsigned int, unsigned long
	with 'L':	long, unsigned long
	with 'UL':	unsigned long
	decimal:	int, long, unsigned long
	octal, hex:	int, unsigned int, long, unsigned long
(So 2147483648 is long but 0x80000000-0xffffffff are unsigned int.)

Character constants are "int".
String literals are arrays of "char".

Null pointer constants:
	any zero-valued integral constant expression,
	possibly cast to (void *)


Operator Precedence and Associativity
-------------------------------------

These are the classes of operators in decreasing order of precedence.

	(x)
	postfix:	x[y], x(...), x.y, x->y, x++, x--
	prefix:		++x, --x, (type) x, sizeof x, &x, *x, +x, -x, ~x, !x
	multiplicative:	x*y, x/y, x%y
	additive:	x+y, x-y
	shift:		x<<y, x>>y
	relational:	x<y, x<=y, x>y, x>=y
	equality:	x==y, x!=y
	bitwise and:	x&y
	bitwise xor:	x^y
	bitwise or:	x|y
	logical and:	x&&y
	logical or:	x||y
	conditional:	x?y:z
	assignment:	x=y and *= /= %= += -= <<= >>= &= ^= |=
	sequence:	x,y

All binary operators are left-associative where it makes a difference,
except of course for assignment.  The conditional x?y:z operator
is the ONLY doubtful case that is right-associative!

	So	x ? y : a ? b : c
	is	x ? y : (a ? b : c)
	not	(x ? y : a) ? b : c

Some syntactic equivalences:
	x->y	means	(*x).y
	x[y]	means	*(x+y)
	!x	means	x == 0

Rules applying to x.y and *x may thus apply to x->y or x[y] as well.
Note that "!!x" is equivalent to "x != 0".


Notes on Operators
------------------

Pointer arithmetic is always in units of the pointer's base
type.  This means that adding or subtracting an integer to or
from a pointer yields a pointer to another element in the
same array.

	p + 1 == &p [1]

Subtracting two pointers yields a distance that is also in
units of the pointer's base type.

These operators always return either 0 or 1:

	!x
	relations and equalities (<, <=, >, >=, ==, !=)
	x && y
	x || y

The logical operators (x && y, x || y) do not evaluate their
second operands if the first operand determines the result.


On two's-complement processors,
	-x == ~x + 1
	~x == -1 - x
	x & -(1<<y)	lowers x to a multiple of a power of two
	(1 << x) - y == y ^ ((1 << x) - 1)
	(x&y) + (x|y) == x + y == (x^y) + ((x&y) << 1)

Note that sizeof (type) requires parenthese, while sizeof expression
does not.



Lvalues
-------

An Lvalue represents the location of an object or function, and
might be the target of assignment.  An Rvalue is any other value,
such as an object's value or a constant or a function result.

Only these expressions are Lvalues:

	identifiers of objects and functions
	"string literal"
	(Lvalue)
	Lvalue.member
	*Rvalue

x.y is an Lvalue if x is, and has all the qualifiers of
the types of both x and y.  Casts are not Lvalues.
As a consequence of the syntactic equivalences noted above,
these expressions are also Lvalues:

	Rvalue->member
	Rvalue [Rvalue]


An Lvalue is modifiable if its type is none of these:
	function
	array
	incomplete
	const-qualified
	struct/union with any unmodifiable member


Implicit Promotions, Conversions, and Operations
------------------------------------------------

Lvalues (other than arrays and functions) become Rvalues of
unqualified type except in these contexts:
	sizeof
	&x
	x++, x--, ++x, --x
	x.member
	left sides of assignments (x=..., x+=..., etc.)

Lvalues of array type are converted to Rvalues of pointer type
pointing to their first members except in these contexts:
	sizeof
	&x
	"string literal" in a character array initializer

There are no Rvalues of array type in C outside sizeof.

Function designators are converted to Rvalues of pointer to
function type (except in &x which does that anyway).
So if "f" is the name of a function, all of these are synonyms,
and all have type "pointer to function":

	f
	*f
	***f
	************************************f

Integral promotions: Rvalues of these types (plain, signed,
and unsigned) become "int" or "unsigned int":
	char
	short
	bitfields of type int or smaller
	enum

The famous Usual Arithmetic Conversions:
Given two operands to a binary operator, find the first type
in this list that matches one of the operands, then convert
the other operand to that type.

	long double
	double
	float
	(apply integral promotion, then)
		unsigned long
		long + unsigned -> long or unsigned long
		long
		unsigned
		int

Function argument conversions in the absence of argument types:
	integral promotions
	float -> double

There is an implicit "x != 0" in

	if (x)
	while (x)
	do while (x)
	for (; x; )
	x && x
	x || x
	x ? y : z

An explicit "x != 0" in these contexts serves no semantic purpose.
And "x == 0" in these contexts might be better written as "!x".


Scopes, Namespaces, and Linkage
-------------------------------

Scopes:
	file
	block
	entire function body (for labels)
	prototype

Beware struct/union/enum tags in prototype scopes.

Distinct namespaces (per scope):
	struct/union/enum tags
	labels
	everything else

Storage classes determine linkage of names thus:

	if "static" {
		if file scope
			linkage is internal
		else
			no linkage
	} else if "extern" or a function {
		if a declaration is visible at file scope
			link to it
		else
			linkage is external
	} else if file scope
		linkage is external
	else
		no linkage

Object declarations with initializers and function declarations
with bodies are definitions.  Object declarations without
initializers are tentative definitions with zero fill if
they are not "extern".


Translation Steps
-----------------

A C compiler must behave as if each of these steps were completely
performed before proceeding.

	Turn end-of-line indicators into newlines and replace ??trigraphs
	Delete all backslash-newline pairs
	Form tokens and replace comments by single spaces
	Preprocessing and macro expansion
	Process \escape sequences in 'character constants' and "string literals"
	Delete white space, including newlines
	Concatenate adjacent "string literals"
	Parse and generate code
	Link

Posted by neodelicious
|
주로 시리얼 통신에서 Error 검출을 위해서 CRC을 이용한다.

CRC16 방식을 많이 봤는데, 주로 다음 계산 방식을 이용한다.
CRC-16-IBM - x16 + x15 + x2 + 1 (USB, many others; also known as "CRC-16")

이 CRC이 다양하고 또한 해당 CRC에 대해서도 계산 정책이 다양할 수 있다는 것을 알았다.
다음 두 링크를 클릭해 보길 바란다.

http://jwmx.tistory.com/511
http://en.wikipedia.org/wiki/Cyclic_redundancy_check


추가적으로 CRC를 이용하면 Error를 검출할 가능성이 높은 것이지,
CRC를 이용한다고 해서 Error 검출을 확실히 할 수 있는 것은 아니다~!!
Posted by neodelicious
|