iconv_open() 함수는 dest, source 형식으로 인자를 받고
iconv() 함수는 2중 포인터를 사용한다.

#include <iconv.h>

iconv_t iconv_open(const char *tocode, const char *fromcode);
size_t iconv(iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);

iconv_open(TO, FROM);
이므로 반대로 넣으면 이상하게 나온다. 주의요망!

그리고 iconv() 함수는
문자열 변수들은 2중 포인터로 넘겨주고(왜?)
inbytesleft는 strlen(*inbuf) 의 값을
outbytesleft는 strlen(*outbuf) 의 값을 넣어주면된다.

물론 변환에 따라서, 길이가 가변적으로 달라질수 있기 때문에 주의해야 한다.

만약, 변환중 메모리가 넘치게 되면 EILSEQ 에러가 발생하게 되며, (물론 넘치기 전에 데이터는 빼낼수 있다.)
변수의 포인터가 2중 포인터가 아니면
"__gconv: Assertion `outbuf != ((void *)0) && *outbuf != ((void *)0)' failed."
이런 에러를 만나게 될 것이다.


#include "stdio.h"
#include "string.h"
#include "iconv.h"
#include "errno.h"

#define BUFF_SIZE 64

int main()
{
        iconv_t cd = iconv_open("UNICODE", "UTF-8");
        if (cd == (iconv_t)(-1))
        {
                perror("iconv_open");
                return 0;
        }

        char inBuf[BUFF_SIZE] = "Hello world";
        int inBufSize = sizeof(inBuf);

        char outBuf[BUFF_SIZE];
        int outBufSize = sizeof(outBuf);
        memset(outBuf, 0, outBufSize);

        // convert
        size_t readBytes = strlen(inBuf);
        size_t writeBytes = sizeof(outBuf);
        char* in = inBuf;
        char* out = outBuf;

        printf("readBytes:%d writeBytes:%d\n",readBytes,writeBytes);

        if (iconv(cd, &in, &readBytes, &out, &writeBytes) == -1)
        {
                printf("failed to iconv errno:%d EILSEQ:%d\n", errno, EILSEQ);
        }
        else
        {
                int idx;
                printf("in:%x out:%x\n",in,out);
                printf("readBytes:%d writeBytes:%d\n",readBytes,writeBytes);
                for(idx = 0; idx < BUFF_SIZE; idx++)
                {
                        printf("%03d %c %x\t\t", idx, inBuf[idx], inBuf[idx]);
                        printf("%03d %c %x\n", idx, outBuf[idx], outBuf[idx]);
                }
                outBuf[writeBytes] = '\0';
        }

        iconv_close(cd);
        return 0;
}


2010/04/20 - [Linux] - linux iconv 테스트
2010/04/19 - [Linux] - iconv

Posted by 구차니
iconv 유틸리티를 이용해서 일단 변환 테스트.
-f=UTF-8        (UTF-8 문서를)
-t=UNICODE   (유니코드로 변환)
-o result.txt    (result.txt로 출력)

$ cat test.str
Hello world
$ vi test.str
  1 Hello world

$ iconv -f=UTF8 -t=UNICODE test.str -o result.txt

$ cat result.txt
▒▒Hello world
$ vi result.txt
  1 ÿþH^@e^@l^@l^@o^@ ^@w^@o^@r^@l^@d^@
  2 ^@




Posted by 구차니
언어는 &hl
국가는 &gl 로 변수를 넘겨준다.
(웹상에서 언어를 변경할때는 이렇게 되는데 RSS Feed에는 영향을 미치지 못하는 것으로 보인다.)

http://gdata.youtube.com/feeds/api/standardfeeds/regionID/feedID?v=2

http://gdata.youtube.com/feeds/api/standardfeeds/ko/top_rated
위의 주소는, 한국의 top rated를 받아오는 방법이다.

Country Region ID
Australia AU
Brazil BR
Canada CA
Czech Republic CZ
France FR
Germany DE
Great Britain GB
Holland NL
Hong Kong HK
India IN
Ireland IE
Israel IL
Italy IT
Japan JP
Mexico MX
New Zealand NZ
Poland PL
Russia RU
South Korea KR
Spain ES
Sweden SE
Taiwan TW
United States US

[링크 : http://code.google.com/intl/ko-KR/apis/youtube/2.0/reference.html]

http://gdata.youtube.com/schemas/2007/categories.cat?hl=<LANGUAGE>
위의 내용은, 스키마를 언어별로 받아오는 것이다.
간단하게 카테고리별 문자열을 구글에게서 받아올수 있다.(내부적인 번역이 필요없다!)

Language/Locale hl Parameter Value
Chinese (Traditional) zh-TW
Czech cs-CZ
Dutch nl-NL
English (Great Britain, Ireland, Australia and New Zealand) en-GB
English (United States and Canada)
* default value
en-US
French fr-FR
German de-DE
Italian it-IT
Language/Locale hl Parameter Value
Japanese ja-JP
Korean ko-KR
Polish pl-PL
Portuguese (Brazil) pt-BR
Russian ru-RU
Spanish (Spain) es-ES
Spanish (Mexico) es-MX
Swedish sv-SE

[링크 : http://code.google.com/intl/ko-KR/apis/youtube/2.0/reference.html]

Posted by 구차니
http://gdata.youtube.com/feeds/api/
에서 XML 파일을 받으면 기본적으로

<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>

첫번째 페이지, 25개 항목을 받아오도록 되어있다.
즉, 인자를 넘겨주면 다른 값을 볼수도 있다는 의미!

<link rel='previous' type='application/atom+xml'
  href='http://gdata.youtube.com/feeds/api/videos?start-index=1&max-results=25...'/>
<link rel='next' type='application/atom+xml'
  href='http://gdata.youtube.com/feeds/api/videos?start-index=51&max-results=25...'/>

[링크 : http://code.google.com/intl/ko-KR/apis/youtube/2.0/reference.html]


2010.05.07 추가
start-index 는 대소문자 구분하며, 1 부터 시작한다.

'프로그램 사용 > 유튜브(youtube)' 카테고리의 다른 글

youtube api 변동으로 인한 content 태그 변경  (0) 2010.05.13
youtube locale 관련  (0) 2010.04.20
youtube html5  (2) 2010.04.17
Percent encoding = URL Encoding  (0) 2010.04.16
유튜브 fmt 와 t 값  (0) 2010.04.15
Posted by 구차니
Linux2010. 4. 19. 17:13
리눅스에서 cd는 디렉토리를 변경하고,
pwd는 현재 작업 디렉토리를 보여준다.

그걸 api 수준에서 보자면
cd는 chdir() 이고
pwd는 getcwd() 이다.

long getcwd(char *buf, unsigned long size);

#include <unistd.h>
int chdir(const char *path);
int fchdir(int fd);

[링크 : http://linux.die.net/man/3/getcwd]
[링크 : http://linux.die.net/man/3/chdir]


2010.04.20 추가

코드샘플
#include "unistd.h"

void main()
{
	int ret;
	char buff[256];
	
	getcwd(buff, 255);
	printf("%s\n",buff);
	
	ret = chdir("/etc");

	getcwd(buff, 255);
	printf("%s\n",buff);	
}

Posted by 구차니
iconv는 utf 나 iso8859 등, 여러가지 방법으로
문자열 코딩을 변환해주는 역활을 하는 함수/유틸리티이다.

$ man -k iconv
iconv                (1)  - Convert encoding of given files from one encoding to another
iconv                (1p)  - codeset conversion
iconv                (3)  - perform character set conversion
iconv                (3p)  - codeset conversion function
iconv.h [iconv]      (0p)  - codeset conversion facility
iconv_close          (3)  - deallocate descriptor for character set conversion
iconv_close          (3p)  - codeset conversion deallocation function
iconv_open           (3)  - allocate descriptor for character set conversion
iconv_open           (3p)  - codeset conversion allocation function
아무튼, iconv는 함수(3/3p) 이자 유틸리티(1) 인데
함수의 경우 iconv_open() - iconv() - iconv_close() 를 이용하여 사용한다.

#include <iconv.h>
iconv_t iconv_open(const char *tocode, const char *fromcode);

tocode나 fromcode에 들어갈 내용은
명령어로 확인이 가능하다.

$ ldd /usr/bin/iconv
        linux-gate.so.1 =>  (0x005e5000)
        libc.so.6 => /lib/libc.so.6 (0x47ae8000)
        /lib/ld-linux.so.2 (0x47119000)
ldd로 확인해보니, libc만 있으면 실질적으로 구동이 가능한 함수로 보인다.

테스트가 필요한 코드
[링크 : http://kldp.org/node/77391]
[링크 : http://www.korone.net/bbs/board.php?bo_table=etc_misc&wr_id=160&page=2]
Posted by 구차니
개소리 왈왈2010. 4. 18. 20:53
옥상에 어머니의 강력한 추진으로 인해
딸기 12 녀석이 폭폭폭!

아무튼 분홍꽃 / 흰꽃이 있는데 꽃집에서 하는 말이
흰꽃은 열매가 하나만 열리고,
분홍꽃은 열매가 여러개 열린다고 하는데..


머.. 열려 보면 알겠지?

'개소리 왈왈' 카테고리의 다른 글

비온다.  (8) 2010.04.26
참 혹은 거짓. 그리고 경계  (0) 2010.04.21
전 지대로 컴맹이빈다 /ㅁ/  (8) 2010.04.14
매정한 네이버  (12) 2010.04.12
구차니로 컴백합니다  (0) 2010.04.05
Posted by 구차니
IBM 문서인데,
결국 XML 탐색은 tagname이 유일하거나 혹은 name space로 구분함으로서
실질적으로 유일한 tag name을 주어 키워드로 검색하고
그에 따른 child나 parent 이런식으로 검색을 용이하게 하는 것으로 보인다.

결론 : 결국은 범용 XML 리더는 존재하지 않고, 개별 XML 구조에 맞도록 읽어 와야 한다는 것으로 판단됨.

[링크 : http://www.ibm.com/developerworks/kr/library/x-xmlajaxpt1/]
Posted by 구차니
음.. 역시 모든 언어는 skeleton code를 외우면 상대적으로 익히기가 쉬운듯!
(문득 C언어 배울때 #include <stdio.h> void main() {} 하던 기억이.. OTL)

.386
.MODEL Flat, STDCALL
.DATA
; Your initialized data. <comment>
.DATA?
;Your uninitialized data. <comment>
.CONST
.CODE
label:
    end label

[링크 : http://win32assembly.online.fr/tut1.html]

'Programming > Assembly(어셈블리)' 카테고리의 다른 글

.DATA? 지시어  (0) 2011.07.31
x86 register  (2) 2011.07.17
PowerPC(PPC) 어셈관련 내용  (0) 2011.04.04
어셈블리 메모리 참조 (x86 memory addressing)  (0) 2010.05.03
어셈블리 언어  (0) 2010.05.03
Posted by 구차니
Programming/언어론2010. 4. 17. 17:39
convention 은

[링크 : http://engdic.daum.net/dicen/contents.do?query1=E255050]
이런 의미를 가지는데, 굳이 해석하자면, 호출 규약 혹은 관용적인 호출방법 이라고 하면 되려나?

아무튼 문득 Iczelion 의 강좌를 읽다보니 어셈블리 기본 구조에
STDCALL 이라는 용어가 나오고, calling convention 이 나오길래 자세히 읽어 봤더니
'함수를 호출시에 인자를 넘겨주는 데이터를 stack에 넣는 방법'을 의미한다.

.MODEL FLAT, STDCALL
.MODEL is an assembler directive that specifies memory model of your program. Under Win32, there's only on model, FLAT model.
STDCALL tells MASM about parameter passing convention. Parameter passing convention specifies the order of  parameter passing, left-to-right or right-to-left, and also who will balance the stack frame after the function call.
Under Win16, there are two types of calling convention, C and PASCAL
C calling convention passes parameters from right to left, that is , the rightmost parameter is pushed first. The caller is responsible for balancing the stack frame after the call. For example, in order to call a function named foo(int first_param, int second_param, int third_param) in C calling convention the asm codes will look like this:

push  [third_param]               ; Push the third parameter
push  [second_param]            ; Followed by the second
push  [first_param]                ; And the first
call    foo
add    sp, 12                                ; The caller balances the stack frame
PASCAL calling convention is the reverse of C calling convention. It passes parameters from left to right and the callee is responsible for the stack balancing after the call.
Win16 adopts
PASCAL convention because it produces smaller codes. C convention is useful when you don't know how many parameters will be passed to the function as in the case of wsprintf(). In the case of wsprintf(), the function has no way to determine beforehand how many parameters will be pushed on the stack, so it cannot do the stack balancing.
STDCALL is the hybrid of C and PASCAL convention. It passes parameter from right to left but the callee is responsible for stack balancing after the call.Win32 platform use STDCALL exclusively. Except in one case: wsprintf(). You must use C calling convention with wsprintf().


[링크 : http://win32assembly.online.fr/tut1.html]

예를 들어, C언어의 경우에는  STDCALL을 사용하며,
인자(argument)들은 오른쪽 부터 stack에 push() 된다.

즉,
push(arg4);
push(arg3);
push(arg2);
push(arg1);
이런식으로 함수 호출시 인자를 넘겨주게 된다.


음.. 개인적인 생각이지만, C언어의 경우 heap은 아래에서 위로 커나가는데 그 방향을 맞추려고
stack에도 데이터를 이렇게 반대 순서로 넣는게 아닐까 싶다.

물론 argument 순서가 의미는 없기 때문에(받아들이는 쪽에서 알아서 받는다면)
가장 위에 첫 인자가 있을 이유는 없는데, 굳이 이런식으로 방향성을 가진다는건...
메모리 구조에 기인한게 아닐려나?

(아니면 말구 -ㅁ-!)

'Programming > 언어론' 카테고리의 다른 글

일급 함수 first-class function  (0) 2025.01.31
dangling if-else  (0) 2014.08.13
double의 정확도 자릿수  (0) 2011.03.25
함수 포인터 (function pointer)  (0) 2010.09.16
type system  (0) 2010.09.15
Posted by 구차니