Computer Programming Practice (2011 Winter) Practice 12 Standard C Libraries The Last Practice 2012. 01. 25
2/24 Contents Standard C Libraries Input & Output Functions : stdio.h String Functions : string.h Utility Functions : stdlib.h Man page
3/24 Input & Output Functions (1/3) Header : <stdio.h> fseek, ftell, rewind, fsetpos, fgetpos : File positioning functions Usage #include <stdio.h> int fseek(file *stream, long offset, int whence); long ftell(file *stream); void rewind(file *stream); int fgetpos(file *stream, fpos_t *pos); int fsetpos(file *stream, fpos_t *pos); // fpos_t 는 Stream 의 File Position 에대한정보를지닌 struct 이다.
Input & Output Functions (2/3) fseek, ftell, rewind, fsetpos, fgetpos (cont.) Description fseek() 함수는 stream 에서의위치를변경하기위해서사용한다. 새로운위치는 offset 을통해서바이트단위로지정할수있다. 위치변경을위해서는기준점이있어야하는데, 이는 whence 를이용해서결정할수있다. whence 는위치변경을위한기준점에따라서 SEEK_SET, SEEK_CUR, 및 SEEK_END 가있다. SEEK_SET 는시작점을, SEEK_CUR 은현재스트림에서의위치를, 그리고 SEEK_END 는스트림의마지막점을기준으로한다. ftell() 함수는 stream 에서의현재위치를구하기위해서사용한다. rewind() 함수는 stream 에서의위치를처음으로되돌리기위해서사용한다. rewind() 는 fseek() 를이용해서동일하게구현할수있다. (void)fseek(stream, 0L, SEEK_SET) fgetpos() 및 fsetpos() 는 ftell() 과 fseek() 의조합 (whence 는 SEEK_SET) 이다. 즉위치를변경하고현재의위치값을 fpos_t 객체에되돌려준다. 4/24
Input & Output Functions (3/3) fseek, ftell, rewind, fsetpos, fgetpos (cont.) Return value rewind() 함수는아무것도되돌려주지않는다. fgetpos(), fseek(), 및 fsetpos() 는 0 을, 그리고 ftell() 는현재위치를되돌려준다. 실패했을경우에는 -1 을리턴한다. Error (Error 발생시다음과같은 Constant 가 <error.h> Header 안에선언된 errno 변수에지정된다.) EBADF stream 이위치를정할수없는스트림이다. STDOUT 및 STDIN 이대표적인위치를정할수없는스트림이다. EINVAL whence 인자가 SEEK_SET, SEEK_END, 및 SEEK_CUR 이아닌값을사용했다. EINTR 시스템호출이인터럽트되었다. 5/24
6/24 Input & Output Functions Example (1/3) #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { FILE *fp; char buf[256]; char gline[12]; int linenum = 0; int inputline; int *line_index; int i fp = fopen(argv[1], "r"); if (fp == NULL){ perror("open error"); return 1; // 라인의갯수를계산한다. while(fgets(buf, 255, fp)!= NULL){ if (buf[strlen(buf)-1] == '\n') linenum++; // 라인의갯수만큼메모리를할당한다. // line_index 배열에는각라인의위치가들어간다. line_index = (int *)malloc(sizeof(int) * linenum +1);
7/24 Input & Output Functions Example (2/3) // 스트림을처음으로되돌린다. rewind(fp); linenum = 0; // 파일의처음부터돌면서 ftell() 을이용하여 // 각라인의위치 (offset) 를저장한다. line_index[0] = 0; while(fgets(buf, 255, fp)!= NULL){ // Add: 라인의크기가 255 를초과할경우이에대해처리한다. if (buf[strlen(buf)-1] == '\n'){ line_index[linenum+1] = ftell(fp); linenum ++; printf("line num is %d\n", linenum);
Input & Output Functions Example (3/3) // 라인번호를입력하면해당라인으로 // fseek() 함수를이용해서점프하고라인의내용을출력한다. while(1){ printf("goto Line : "); fgets(gline, 11, stdin); if ( gline[0] == 'q' ) break; gline[strlen(gline) - 1] = '\0'; inputline = atoi(gline); if (inputline < linenum && inputline > -1){ fseek(fp, line_index[inputline], SEEK_SET); fgets(buf, 255, fp); printf("%d(%d) : %s", inputline, line_index[inputline],buf); else { printf("input num Error (0 - %d)\n", linenum-1); printf("\n"); free(line_index); return 0; Source : /home/comp-ta/prac12/file/file_ex.c 8/24
9/24 String Functions (1/7) Header : <string.h> strcmp, strncmp Usage int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); Description 두문자열 s1 과 s2 를비교한다. 만약 s2 가 s1 보다작다면음수를같다면 0 을, 크다면양수를리턴한다. 두문자가같을경우 0 을반환한다는점에주의한다. 많은프로그래머가관례상 if(strcmp(s1, s2)) 와같은방식으로문자가같음을검사하는실수를하는경우가있다.
10/24 String Functions (2/7) strcmp, strncmp (cont.) Return value s1 과 s2 가같으면 0, s2 가 s1 보다작으면음수, s2 가 s1 보다크다면양수를반환한다. #include <stdio.h> #include <string.h> int main() { char buf[80]; while (fgets(buf, 80, stdin)!= NULL) { buf[strlen(buf)-1] = 0x00; if(strcmp(buf, "exit") == 0) break; printf("input string : %s\n", buf); return 0; Source : /home/comp-ta/prac12/string/strcmp_ex.c
11/24 String Functions (3/7) strstr Usage char *strstr(const char *haystack, const char *needle); Description strstr 함수는문자열 haystack 에서 needle 이처음발견되는곳을찾는다. Return value 만약 haystack 에서 needle 을찾는다면처음발견된위치의포인터를반환한다. 만약 needle 이발견되지않는다면 NULL 을반환한다.
12/24 String Functions (4/7) strstr (cont.) #include <stdio.h> #include <string.h> Example int main() { char *me = "my name=comp-ta"; char *mp; mp = strstr(me, "=")+1; printf("%s\n", mp); return 0; Source : /home/comp-ta/prac12/string/strstr_ex.c
String Functions (5/7) strtok Usage char *strtok(char *s, const char *delim); Description ` 토큰 ` 이란문자열 delim 에속하지않는문자들로이루어진비어있지않은문자열이며 \0 이나 delim 에있는문자가뒤따른다. strtok() 함수는문자열 s 를토큰으로파싱하기위해사용된다. strtok() 의첫번째인자로 s 를주면, 가장앞에있는토큰을구하고, 그문자열안의다음토큰을구하고자할때에는첫번째인자를 NULL 로설정하여야한다. 각호출은다음토큰에대한포인터를반환하거나더이상토큰이발견되지않는다면 NULL 을반환한다. 토큰이구분자로끝난다면, 이구분자는 \0로겹쳐쓰여지며다음문자에대한포인터가 strtok() 에대한다음호출을위해저장된다. 구분문자열 delim는각호출시다를수있다. 13/24
String Functions (6/7) strtok (cont.) #include <stdio.h> #include <string.h> Return value int main() { char str[] ="This is a sample string,just testing."; char *pch; 다음토큰에대한포인터를반환하거나만일더이상토큰이없다면 NULL 을반환한다. printf("splitting string \"%s\" in tokens:\n",str); pch = strtok(str," "); while(pch!= NULL) { printf("%s\n",pch); pch = strtok (NULL, ",."); return 0; Source : /home/comp-ta/prac12/string/strtok_ex.c 14/24
15/24 String Functions (7/7) Other functions strchr, strrchr char *strchr(const char *s, int c); strchr 은문자배열 s 내에문자 c 가있는지검사하고있을경우문자 c 가있는번지를리턴한다. strrchr 은 strchr 과비슷하나문자열의뒤에서부터찾는것이 strchr 과틀리다.
16/24 Utility Functions (1/5) Header : <stdlib.h> atoi, atof Usage int atoi(const char *nptr); double atof(const char *nptr); Description atoi() 함수는 nptr 로지정된스트링의최초분할값을 int 로변환한다. strtol(nptr, (char **)NULL, 10); 과같은효과를발휘한다. atof() 함수는 nptr 로지정된스트링의최초분할을 double 로변환한다. strtod(nptr, (char **)NULL); 과같은효과를발휘한다.
17/24 Utility Functions (2/5) atoi, atof (cont.) Return value 각각 int 형으로변환된값과 double 형으로변환된값이리턴된다. #include <stdio.h> #include <stdlib.h> int main() { int num_i; double num_d; char *str[2] = { "-123", "3.141592" ; num_i = atoi(str[0]); num_d = atof(str[1]); printf("integer is %d\n", num_i); printf("double is %f\n", num_d); return 0; Source : /home/comp-ta/prac12/lib/ato_ex.c
18/24 Utility Functions (3/5) rand, srand Usage int rand(void); void srand(unsigned int seed); Description rand() 함수는 0 과 RAND_MAX 사이의 pseudo-random 정수를리턴한다. 만일어떤 seed 값도제공되지않는다면, rand() 함수는자동적으로 1 을 seed 값으로한다. srand() 함수는인자를 rand() 가리턴하는 pseudo-random 정수의새로운연속된수들을위한 Seed Value 로설정한다. 이들연속된수들은같은 seed 값으로 srand() 를호출하여반복된다
Utility Functions (4/5) rand, srand (cont.) #include <stdio.h> #include <stdlib.h> Return value int main() { struct timeval tv; printf("%d\n", rand()); printf("%d\n", rand()); printf("%d\n", rand()); printf("\n"); rand() 함수는 0 과 RAND_MAX (2147483647) 사이의값을반환한다. srand() 함수는반환값이없다. gettimeofday(&tv, NULL); srand(tv.tv_usec); printf("%d\n", rand()); printf("%d\n", rand()); printf("%d\n", rand()); return 0; Source : /home/comp-ta/prac12/lib/rand_ex.c 19/24
20/24 Utility Functions (5/5) Other functions atol : string -> long type number strtol : string -> long type number strtod : string -> double type number
21/24 Man page (1/3) Manual page (Man page) an interface to the on-line reference manuals 찾고자하는명령어또는함수등의설명 (manual) 을보여줌 Usage $ man [section number] ( 찾고자하는명령어또는함수명 ) Key b : backward 이전페이지 f : forward 다음페이지 j : 이전한줄 k : 다음한줄 q : 종료
22/24 Man page (2/3) Sections 1 : 사용자명령 (User Commands) 2 : 시스템호출 (System Calls) 3 : C 라이브러리함수 (C Library functions) 4 : 디바이스와네트워크인터페이스 (Devices and Network Interfaces) 5 : 파일포맷 (File Formats) 6 : 게임과데모 (Games and Demos) 7 : 환경, 테이블, 매크로 (Environments, Tables, a nd Macros) 8 : 시스템관리 (Maintenance Commands)
23/24 Man page (3/3) Name Section Number
24/24 Reference Manpage Project http://man.kldp.org/wiki/manpage