Computer Programming (2008 Fall)

Similar documents
chap7.key

歯9장.PDF

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

금오공대 컴퓨터공학전공 강의자료

슬라이드 1

PA for SWE2007

Microsoft PowerPoint - 제9강 문자열

untitled

제1장 Unix란 무엇인가?

BMP 파일 처리

PA for SWE2007

PA0 for SSE2033

슬라이드 1

À©µµ³×Æ®¿÷ÇÁ·Î±×·¡¹Ö4Àå_ÃÖÁ¾

11장 포인터


Microsoft PowerPoint - chap11-포인터의활용.pptx

PowerPoint 프레젠테이션

Microsoft PowerPoint - 06_(C_Programming)_(Korean)_Characters_Strings

PowerPoint 프레젠테이션

컴파일러

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

Microsoft PowerPoint - chap10-함수의활용.pptx

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4

PowerPoint 프레젠테이션

금오공대 컴퓨터공학전공 강의자료

Microsoft PowerPoint - chap4 [호환 모드]

Microsoft PowerPoint - chap06-2pointer.ppt

이번장에서학습할내용 동적메모리란? malloc() 와 calloc() 연결리스트 파일을이용하면보다많은데이터를유용하고지속적으로사용및관리할수있습니다. 2

untitled

Microsoft PowerPoint - chap12-고급기능.pptx

제1장 Unix란 무엇인가?

임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C D616E2E637070>

제1장 Unix란 무엇인가?

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

ABC 11장

Microsoft PowerPoint - C프로그래밍-chap15.ppt [호환 모드]

PowerPoint Template

K&R2 Reference Manual 번역본

Poison null byte Excuse the ads! We need some help to keep our site up. List 1 Conditions 2 Exploit plan 2.1 chunksize(p)!= prev_size (next_chunk(p) 3

중간고사

제12장 파일 입출력

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

<4D F736F F F696E74202D20C1A63132B0AD20B5BFC0FB20B8DEB8F0B8AEC7D2B4E7>

13 주차문자열의표현과입출력


A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning

Microsoft PowerPoint - ch07 - 포인터 pm0415

11장 포인터

본 강의에 들어가기 전

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2

Microsoft PowerPoint - 09_(C_Programming)_(Korean)_File_Processing

C 언어 프로그래밊 과제 풀이

Microsoft PowerPoint - 제11강 파일 처리

<4D F736F F F696E74202D D20B9AEC0DABFAD2C20BDBAC6AEB8B2B0FA20C6C4C0CF20C0D4C3E2B7C2>

chap8.PDF

untitled

11장 포인터

PowerPoint 프레젠테이션

Microsoft PowerPoint - 11_C_Language_C_Standard_Library

Microsoft PowerPoint - [2009] 02.pptx

C Programming

설계란 무엇인가?

chap 5: Trees

2007_2_project4

Microsoft PowerPoint - chap-12.pptx

C# Programming Guide - Types

Microsoft PowerPoint - chap11.ppt [호환 모드]

윤성우의 열혈 TCP/IP 소켓 프로그래밍

ABC 11장

PowerPoint Presentation

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

Microsoft PowerPoint - Chapter_08.pptx

Microsoft PowerPoint - chap06-8 [호환 모드]

Microsoft PowerPoint - 7_배열_문자열

untitled

1 장 C 언어복습 표준입출력배열포인터배열과포인터함수 const와포인터구조체컴파일러사용방법 C++ 프로그래밍입문

PowerPoint 프레젠테이션

강의10

歯7장.PDF

Microsoft PowerPoint - chap03-변수와데이터형.pptx

chap7.PDF

Microsoft PowerPoint 유용한 PHP 함수들.ppt

이번장에서학습할내용 문자표현방법 문자열표현방법 문자열이란무엇인가? 문자열의입출력 문자처리라이브러리함수 표준입출력라이브러리함수 인간은문자를사용하여정보를표현하므로문자열은프로그램에서중요한위치를차지하고있다. 이번장에서는 C 에서의문자열처리방법에대하여자세히살펴볼것입니다. 2

OCW_C언어 기초

PowerPoint 프레젠테이션

C++-¿Ïº®Çؼ³10Àå

API 매뉴얼

Microsoft PowerPoint - Lesson13.pptx

Microsoft PowerPoint - chap06-5 [호환 모드]

Microsoft PowerPoint - ch10 - 이진트리, AVL 트리, 트리 응용 pm0600

Microsoft PowerPoint - chap06-8.ppt

Transcription:

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