PowerPoint 프레젠테이션

Similar documents
PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

2009년 상반기 사업계획

<4D F736F F F696E74202D FC6C4C0CF20C0D4C3E2B7C2205BC8A3C8AF20B8F0B5E55D>

chap7.key

슬라이드 1

제1장 Unix란 무엇인가?

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

제12장 파일 입출력

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

歯9장.PDF

PowerPoint 프레젠테이션

2009년 상반기 사업계획

Microsoft PowerPoint APUE(File InO).pptx

PowerPoint 프레젠테이션

Microsoft PowerPoint APUE(File InO)

Microsoft PowerPoint APUE(File InO).ppt

Microsoft PowerPoint - 제11강 파일 처리

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

Microsoft PowerPoint - ch09_파이프 [호환 모드]

2009년 상반기 사업계획

제1장 Unix란 무엇인가?

<4D F736F F F696E74202D2034C5D8BDBAC6AEC6C4C0CFC0D4C3E2B7C2312E505054>

Microsoft PowerPoint - chap4 [호환 모드]

제1장 Unix란 무엇인가?

PowerPoint Template

슬라이드 1

Microsoft PowerPoint - Lecture 4-1 Linux File Environment.ppt [호환 모드]

C Programming

로봇SW교육원 강의자료

PowerPoint 프레젠테이션

로봇SW교육원 강의자료

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

11장 포인터

Microsoft PowerPoint - chap2

Microsoft PowerPoint APUE(Intro).ppt

Microsoft PowerPoint - Chap14_FileAccess.pptx

Microsoft PowerPoint - Lesson13.pptx

PowerPoint 프레젠테이션

<4D F736F F F696E74202D FB8DEB8F0B8AE20B8C5C7CE205BC8A3C8AF20B8F0B5E55D>

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

2009년 상반기 사업계획

슬라이드 1

BMP 파일 처리

Microsoft PowerPoint - 10_C_Language_Text_Files

제7장 C 표준 파일 입출력

제7장 C 표준 파일 입출력

untitled

Microsoft PowerPoint - chap12 [호환 모드]

Computer Programming (2008 Fall)

10.


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

11장 포인터

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

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

6주차.key

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

Microsoft PowerPoint - 09_FileSystem

ABC 11장

ABC 11장

Microsoft PowerPoint - 09-Pipe

학번 : 이름 : 1. 다음파일트리구조를가진유닉스시스템이있다. / /bin/ /home/ /home/taesoo/ /home/taesoo/downloads /usr/ /usr/lib/ /usr/local/lib /media 모든폴더에파일이하나도없다고가정했을때사용자 (t

<4D F736F F F696E74202D FC6C4C0CFB0FA20B5F0B7BAC5E4B8AE205BC8A3C8AF20B8F0B5E55D>

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

학번 : 이름 : 1. 다음파일트리구조를가진유닉스시스템이있다고가정하자. / /bin/ /home/ /home/taesoo/ /usr/ /usr/lib/ /usr/local/lib /media 모든폴더에파일이하나도없다고가정했을때사용자가터미널에서다음 ls 명령입력시화면출력

PowerPoint 프레젠테이션

/chroot/lib/ /chroot/etc/

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

PowerPoint 프레젠테이션

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C D616E2E637070>

PowerPoint 프레젠테이션

Microsoft PowerPoint - chap6 [호환 모드]

PowerPoint 프레젠테이션

untitled

데이타전송

<4D F736F F F696E74202D FC7C1B7CEBCBCBDBA20BBFDBCBAB0FA20BDC7C7E0205BC8A3C8AF20B8F0B5E55D>

2009년 상반기 사업계획

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

Microsoft PowerPoint - [2009] 02.pptx

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

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

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

<4D F736F F F696E74202D20C1A63136C0E520C6C4C0CFC0D4C3E2B7C2>

Microsoft PowerPoint - 11_C_Language_C_Standard_Library

Microsoft PowerPoint - chap1 [호환 모드]

<4D F736F F F696E74202D20C1A63137C0E520B5BFC0FBB8DEB8F0B8AEBFCD20BFACB0E1B8AEBDBAC6AE>

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

3. 다음그림은프로세스의 file table 과 v-node 테이블의연결관계예제이다. 위그림을참고하여두개의서로다른프로세스가같은파일을 open 명령을사용하여열었을때의연결관계를도시하시오. 4. 메모리영역은 low-address 부터 high-adress 까지순서대로나열했을

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

표준입출력스트림 기본적인스트림들은프로그래머가생성하지않아도자동으로생성된다. 이름스트림연결장치 stdin 표준입력스트림키보드 stdout 표준출력스트림모니터의화면 stderr 표준오류스트림모니터의화면 입출력함수의분류 사용하는스트림에따른분류 표준입출력스트림을사용하여입출력을하

교육지원 IT시스템 선진화

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

2009년 상반기 사업계획

11장 포인터

PowerPoint 프레젠테이션


Microsoft PowerPoint - lab14.pptx

Transcription:

Error and Command Line Arguments Jo, Heeseung

학습목표 오류처리함수동적메모리할당명령행인자 2

오류처리함수 [1] 오류메시지출력 : perror(3) #include <stdio.h> void perror(const char *s); [ 예제 1-4] perror 함수사용하기 01 #include <sys/errno.h> 02 #include <unistd.h> 03 #include <stdlib.h> 04 #include <stdio.h> 05 06 int main(void) { 07 if (access("unix.txt", R_OK) == -1) { 08 perror("unix.txt"); 09 exit(1); 10 } 11 12 return 0; 13 } # ex1_4.out unix.txt: No such file or directory 오류에따라메시지자동출력 3

오류처리함수 [2] 오류메시지출력 : strerror(3) #include <string.h> char *strerror(int errnum); [ 예제 1-5] strerror 함수사용하기 01 #include <sys/errno.h> 02 #include <unistd.h> 03 #include <stdlib.h> 04 #include <stdio.h> 05 #include <string.h> 06 07 extern int errno; 08 09 int main(void) { 10 char *err; 11 12 if (access("unix.txt", R_OK) == -1) { 13 err = strerror(errno); 14 printf(" 오류 :%s(unix.txt)\n", err); 15 exit(1); 16 } 17 18 return 0; 19 } 오류에따라메시지를리턴 # ex1_5.out 오류 : No such file or directory(unix.txt) 4

동적메모리할당 [1] 메모리할당 : malloc(3) 인자로지정한크기의메모리할당 #include <stdlib.h> void *malloc(size_t size); char *ptr ptr = malloc(sizeof(char) * 100); 메모리할당과초기화 : calloc(3) nelem * elsize 만큼의메모리를할당하고, 0 으로초기화 #include <stdlib.h> void *calloc(size_t nelem, size_t elsize); char *ptr ptr = calloc(10, 20); 5

동적메모리할당 [2] 메모리추가할당 : realloc(3) #include <stdlib.h> void *realloc(void *ptr, size_t size); 이미할당받은메모리 (ptr) 에 size 크기의메모리를추가로할당 char *ptr, *new; ptr = malloc(sizeof(char) * 100); new = realloc(ptr, 100); 메모리해제 : free(3) #include <stdlib.h> void free(void *ptr); 사용을마친메모리반납 6

명령행인자 [1] 명령행 : 사용자가명령을입력하는행 명령행인자 : 명령을입력할때함께지정한인자 ( 옵션, 옵션인자, 명령인자등 ) 명령행인자의전달 : main 함수로자동전달 int main(int argc, char *argv[]) [ 예제 1-6] 명령행인자출력하기 01 #include <stdio.h> 02 03 int main(int argc, char *argv[]) { 04 int n; 05 06 printf("argc = %d\n", argc); 07 for (n = 0; n < argc; n++) 08 printf("argv[%d] = %s\n", n, argv[n]); 09 10 return 0; 11 } # ex1_6.out -h 100 argc = 3 argv[0] = ex1_6.out argv[1] = -h argv[2] = 100 7

명령행인자 [2] 옵션처리함수 : getopt(3) #include <stdio.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; argc, argv : main 함수에서받은것을그대로지정 optstring : 사용할수있는옵션문자 - 옵션에인자가있을경우문자뒤에 ':' 추가 optarg : 옵션의인자저장 optind : 다음에처리할 argv 의주소 optopt : 오류를발생시킨문자 opterr : 오류메시지를출력하지않으려면 0 으로지정 유닉스명령의옵션규칙 옵션의이름은한글자 인자가없는옵션은하나의 - 다음에묶여서올수있음 (-xvf) 인자가있어야하는옵션에서인자를생략할수없음 명령행에서모든옵션은명령의인자보다앞에와야함 8

명령행인자 [3] [ 예제 1-7] getopt 함수사용하기 01 #include <stdio.h> 02 03 int main(int argc, char *argv[]) { 04 int n; 05 extern char *optarg; 06 extern int optind; 07 08 printf("current Optind : %d\n", optind); 09 while ((n = getopt(argc, argv, "abc:"))!= -1) { 10 switch (n) { 11 case 'a': 12 printf("option : a\n"); 13 break; 14 case 'b': 15 printf("option : b\n"); 16 break; 17 case 'c': 18 printf("option : c, Argument=%s\n", optarg); 19 break; 20 } 21 printf("next Optind : %d\n", optind); 22 } 23 24 return 0; 25 } # ex1_7.out Current Optind : 1 # ex1_7.out -a Current Optind : 1 Option : a Next Optind : 2 # ex1_7.out -c Current Optind : 1 ex1_7.out: option requires an argument -- c Next Optind : 2 # ex1_7.out -c name Current Optind : 1 Option : c, Argument=name Next Optind : 3 # ex1_7.out -x Current Optind : 1 ex1_7.out: illegal option -- x Next Optind : 2 9

File I/O Jo, Heeseung

학습목표 유닉스에서파일입출력의특징을이해저수준파일입출력함수를사용고수준파일입출력함수를사용임시파일을생성해파일입출력 11

목차 저수준파일입출력 파일기술자 파일생성과열고닫기 파일읽기와쓰기 파일오프셋지정 파일기술자복사 파일기술자제어 파일삭제 고수준파일입출력 파일포인터 파일열기와닫기 문자기발입출력 문자열기반입출력 버퍼기반입출력 형식기반입출력 파일오프셋지정 파일기술자와파일포인터간변환 12

파일기술자 (file descriptor) 파일기술자 (file descriptor) 현재열려있는파일을구분하는정수값 저수준파일입출력에서열린파일을참조하는데사용 - 0 : 표준입력 - 1 : 표준출력 - 2 : 표준오류 13

파일생성과열고닫기 [1] 파일열기 : open(2) #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *path, int oflag [, mode_t mode]); path 에지정한파일을 oflag 에지정한플래그값에따라열고파일기술자를리턴 oflag 값 종류 기능 O_RDONLY 파일을읽기전용으로연다. O_WRONLY 파일을쓰기전용으로연다. O_RDWR 파일을읽기와쓰기가가능하게연다. O_CREAT 파일이없으면파일을생성한다 O_EXCL O_CREAT 옵션과함께사용할경우기존에없는파일이면파일을생성하지만, 파일이이미있으면파일을생성하지않고오류메시지를출력한다. O_APPEND 파일의맨끝에내용을추가한다. O_TRUNC 파일을생성할때이미있는파일이고쓰기옵션으로열었으면내용을모두지우고파일의길이를 0으로변경한다. O_NONBLOCK/O_NDELAY 비블로킹 (Non-blocking) 입출력 O_SYNC/O_DSYNC 저장장치에쓰기가끝나야쓰기동작을완료 14

파일생성과열고닫기 [2] 파일열기 : open(2) mode: 파일접근권한지정, 0644 같이숫자나플래그값으로지정가능 mode=s_irusr S_IWUSR; 15

파일생성과열고닫기 [3] 파일닫기 : close(2) #include <unistd.h> int close(int fildes); 프로세스에서열수있는파일개수가제한되어있으므로파일의사용이끝나면닫아야함 16

[ 예제 2-1] 새파일열고닫기 01 #include <sys/types.h> 02 #include <sys/stat.h> 03 #include <fcntl.h> # ls unix.txt 04 #include <unistd.h> 05 #include <stdlib.h> unix.txt: 해당파일이나디렉토리가없음 06 #include <stdio.h> # gcc -o ex2_1.out ex2_1.c 07 08 int main(void) { # ex2_1.out# ls -l unix.txt 09 int fd; -rw-r--r-- 1 root other 0 1월 6일 13:10 unix.txt 10 mode_t mode; 11 12 mode = S_IRUSR S_IWUSR S_IRGRP S_IROTH; 13 접근권한 :644 14 fd = open("unix.txt", O_CREAT, mode); 15 if (fd == -1) { 16 perror("creat"); 17 exit(1); 18 } 19 close(fd); 20 21 return 0; 22 } 17

[ 예제 2-2] O_EXCL 플래그사용하기 01 #include <sys/types.h> 02 #include <sys/stat.h> 03 #include <fcntl.h> 04 #include <unistd.h> 05 #include <stdlib.h> 06 #include <stdio.h> 07 08 int main(void) { 09 int fd; 10 11 fd = open("unix.txt", O_CREAT O_EXCL, 0644); 12 if (fd == -1) { 13 perror("excl"); 14 exit(1); 15 } 16 close(fd); 17 18 return 0; 19 } # ls unix.txt unix.txt # ex2_2.out Excl: File exists # rm unix.txt # ex2_2.out # ls unix.txt unix.txt 18

파일읽기와쓰기 파일읽기 : read(2) #include <unistd.h> ssize_t read(int fildes, void *buf, size_t nbytes); 파일에서 nbytes 로지정한크기만큼바이트를읽어서 buf 에저장 실제로읽어온바이트개수를리턴 리턴값이 0 이면파일의끝에도달했음을의미 파일의종류에상관없이무조건바이트단위로읽어옴 파일쓰기 : write(2) #include <unistd.h> ssize_t write(int fildes, const void *buf, size_t nbytes); buf 가가리키는메모리에서 nbytes 로지정한크기만큼파일에기록 실제로쓰기를수행한바이트수를리턴 20

[ 예제 2-5] 파일읽고쓰기... 06 int main(void) { 07 int rfd, wfd, n; 08 char buf[10]; 09 10 rfd = open("unix.txt", O_RDONLY); 11 if(rfd == -1) { perror("open unix.txt"); 13 exit(1); 14 } 15 파일기술자 2 개선언 16 wfd = open("unix.bak", O_CREAT O_WRONLY O_TRUNC, 0644); 17 if (wfd == -1) { 18 perror("open unix.bak"); 19 exit(1); 20 } 21 22 while ((n = read(rfd, buf, 6)) > 0) 23 if (write(wfd, buf, n)!= n) perror("write"); 24 6 바이트씩읽어온다 21

[ 예제 2-5] 파일읽고쓰기 25 if (n == -1) perror("read"); 26 27 close(rfd); 28 close(wfd); 29 30 return 0; 31 } # ls unix.bak unix.bak: 해당파일이나디렉토리가없음 # ex2_5.out # cat unix.bak Unix System Programming 22

파일오프셋지정 파일오프셋위치지정 : lseek(2) #include <sys/types.h> #include <unistd.h> off_t lseek(int fildes, off_t offset, int whence); offset 으로지정한크기만큼오프셋을이동 offset 의값은 whence 값을기준으로해석 lseek(fd, 5, SEEK_SET); lseek(fd, 0, SEEK_END); 파일의시작에서 5 번째위치로이동 파일의끝에서 0 번째, 즉끝으로이동 파일오프셋의현재위치를알려면? cur_offset = lseek(fd, 0, SEEK_CUR); 23

[ 예제 2-6] 파일오프셋사용하기... 07 int main(void) { 08 int fd, n; 09 off_t start, cur; 10 char buf[256]; 11 12 fd = open("unix.txt", O_RDONLY); 13 if (fd == -1) { 14 perror("open unix.txt"); 15 exit(1); 16 } 17 18 start = lseek(fd, 0, SEEK_CUR); 19 n = read(fd, buf, 255); 20 buf[n] = '\0'; 21 printf("offset start=%d, Read Str=%s, n=%d\n", (int)start, buf, n); 22 cur = lseek(fd, 0, SEEK_CUR); 23 printf("offset cur=%d\n", (int)cur); 24 24

[ 예제 2-6] 파일오프셋사용하기 25 start = lseek(fd, 5, SEEK_SET); 26 n = read(fd, buf, 255); 27 buf[n] = '\0'; 28 printf("offset start=%d, Read Str=%s", (int)start, buf); 29 30 close(fd); 31 32 return 0; 33 } # ex2_6.out Offset start=0, Read Str=Unix System Programming, n=24 Offset cur=24 Offset start=5, Read Str=System Programming 25

파일기술자제어 파일기술자제어 : fcntl(2) #include <sys/types.h> #include <unistd.h> #include <fcntl.h> int fcntl(int fildes, int cmd, /* arg */...); 파일기술자가가리키는파일에 cmd 로지정한명령을수행 cmd 의종류에따라인자 (arg) 를지정할수있음 자주사용하는 cmd 29

[ 예제 2-9] fcntl 함수로파일기술자제어하기 07 int main(void) { 08 int fd, flags; 09 10 fd = open("unix.txt", O_RDWR); 11 if (fd == -1) { 12 perror("open"); 13 exit(1); 14 } 15 16 if ((flags = fcntl(fd, F_GETFL)) == -1) { 17 perror("fcntl"); 18 exit(1); 19 } 20 파일을추가모드로수정 21 flags = O_APPEND; 22 23 if (fcntl(fd, F_SETFL, flags) == -1) { 24 perror("fcntl"); 25 exit(1); 26 } 27 28 if (write(fd, "Hanbit Media", 12)!= 12) perror("write"); 29 close(fd); 30 31 파일에내용추가 return 0; 32 } # cat unix.txt Unix System Programming # ex2_9.out # cat unix.txt Unix System Programming Hanbit Media 30

파일삭제 unlink(2) #include <unistd.h> int unlink(const char *path); path에지정한파일의 inode에서링크수를감소 링크수가 0이되면 path에지정한파일이삭제 파일뿐만아니라디렉토리 ( 빈디렉토리아니어도됨 ) 도삭제 remove(3) #include <stdio.h> int remove(const char *path); path 에지정한파일이나디렉토리를삭제 디렉토리인경우빈디렉토리만삭제 31

[ 예제 2-10] unlink 함수로파일삭제하기 01 #include <unistd.h> 02 #include <stdlib.h> 03 #include <stdio.h> 04 05 int main(void) { 06 int cnt; 07 08 cnt = unlink("tmp.aaa"); tmp.aaa 파일삭제 09 if (cnt == -1) { 10 perror("unlink tmp.aaa"); 11 exit(1); 12 } 13 14 printf("unlink tmp.aaa success!!!\n"); 15 16 return 0; 17 } # ls -l tmp* -rw-r--r-- 1 root other 37 1월 6일 17:50 tmp.aaa -rw-r--r-- 1 root other 35 1월 6일 18:06 tmp.bbb # ex2_10.out Unlink tmp.aaa success!!! # ls -l tmp* -rw-r--r-- 1 root other 35 1월 6일 18:06 tmp.bbb 32

파일포인터 고수준파일입출력 : 표준입출력라이브러리파일포인터 고수준파일입출력에서열린파일을가리키는포인터 자료형으로 FILE * 형을사용 -> 구조체에대한포인터 34

파일열기와닫기 [1] 파일열기 : fopen(3) #include <stdio.h> FILE *fopen(const char *filename, const char *mode); filename 으로지정한파일을 mode 로지정한모드에따라열고파일포인터를리턴 mode 값 FILE *fp; fp = fopen("unix.txt", "r"); 35

파일열기와닫기 [2] 파일닫기 : fclose(3) #include <stdio.h> int fclose(file *stream); fopen 으로오픈한파일을닫음 FILE *fp; fp = fopen("unix.txt", "r"); fclose(fp); 36

문자기반입출력함수 문자기반입력함수 : fgetc(3), getc(3), getchar(3), getw(3) #include <stdio.h> int fgetc(file *stream); int getc(file *stream); int getchar(void); int getw(file *stream); fgetc : 문자한개를 unsigned char 형태로읽어옴 getc, getchar : 매크로 getw : 워드단위로읽어옴 문자기반출력함수 : fputc(3), putc(3), putchar(3), putw(3) #include <stdio.h> int fputc(int c, *stream); int putc(int c, *stream); int putchar(int c); int putw(int w, FILE *stream); 37

[ 예제 2-11] 문자기반입출력함수사용하기 01 #include <stdlib.h> 02 #include <stdio.h> 03 04 int main(void) { 05 FILE *rfp, *wfp; 06 int c; 07 08 if ((rfp = fopen("unix.txt", "r")) == NULL) { 09 perror("fopen: unix.txt"); 10 exit(1); 11 } 12 13 if ((wfp = fopen("unix.out", "w")) == NULL) { 14 perror("fopen: unix.out"); 15 exit(1); 16 } 17 18 while ((c = fgetc(rfp))!= EOF) { 19 fputc(c, wfp); 20 } 21 22 fclose(rfp); 23 fclose(wfp); 24 25 return 0; 26 } EOF 를만날때까지한문자씩읽어서 파일로출력 # cat unix.txt Unix System Programming # ex2_11.out # cat unix.out Unix System Programming 38

문자열기반입출력 문자열기반입력함수 : gets(3), fgets(3) #include <stdio.h> char *gets(char *s); char *fgets(char *s, int n, FILE *stream); gets : 표준입력에서문자열을읽음 fgets : 파일 (stream) 에서 n 보다하나적게문자열을읽어 s 에저장 문자열기반출력함수 : puts(3), fputs(3) #include <stdio.h> char *puts(const char *s); char *fputs(const char *s, FILE *stream); 39

[ 예제 2-12] 문자열기반입출력함수사용하기 01 #include <stdlib.h> 02 #include <stdio.h> 03 04 int main(void) { 05 FILE *rfp, *wfp; 06 char buf[bufsiz]; 07 08 if ((rfp = fopen("unix.txt", "r")) == NULL) { 09 perror("fopen: unix.txt"); 10 exit(1); 11 } 12 13 if ((wfp = fopen("unix.out", "a")) == NULL) { 14 perror("fopen: unix.out"); 15 exit(1); 16 } 17 18 while (fgets(buf, BUFSIZ, rfp)!= NULL) { 19 fputs(buf, wfp); 20 } 21 22 fclose(rfp); 23 fclose(wfp); 24 25 return 0; 26 } 한행씩 buf 로읽어서파일로출력 # ex2_12.out # cat unix.out Unix System Programming Unix System Programming 40

버퍼기반입출력 버퍼기반입력함수 : fread(3) #include <stdio.h> size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream); 항목의크기가 size 인데이터를 nitems 에지정한개수만큼읽어 ptr 에저장 성공하면읽어온항목수를리턴 읽을항목이없으면 0 을리턴 버퍼기반출력함수 : fwrite(3) #include <stdio.h> size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream); 항목의크기가 size 인데이터를 nitems 에서지정한개수만큼 ptr 에서읽어서 stream 으로지정한파일에출력 성공하면출력한항목의수를리턴 오류가발생하면 EOF 를리턴 41

[ 예제 2-13] fread 함수로파일읽기 01 #include <stdlib.h> 02 #include <stdio.h> 03 04 int main(void) { 05 FILE *rfp; 06 char buf[bufsiz]; 07 int n; 08 09 if ((rfp = fopen("unix.txt", "r")) == NULL) { 10 perror("fopen: unix.txt"); 11 exit(1); 12 } 13 14 while ((n=fread(buf, sizeof(char)*2, 3, rfp)) > 0) { 15 buf[6] = '\0'; 16 printf("n=%d, buf=%s\n", n, buf); 17 } 18 19 fclose(rfp); 20 21 return 0; 22 } 항목크기가 char 크기의 2 배, 이것을 3 개, 즉 2*3=6 바이트씩읽어서출력 # ex2_13.out n=3, buf=unix S n=3, buf=ystem n=3, buf=progra n=3, buf=mming 42

[ 예제 2-14] fwrite 함수로파일출력하기 01 #include <stdlib.h> 02 #include <stdio.h> 03 04 int main(void) { 05 FILE *rfp, *wfp; 06 char buf[bufsiz]; 07 int n; 08 09 if ((rfp = fopen("unix.txt", "r")) == NULL) { 10 perror("fopen: unix.txt"); 11 exit(1); 12 } 13 14 if ((wfp = fopen("unix.out", "a")) == NULL) { 15 perror("fopen: unix.out"); 16 exit(1); 17 } 18 19 while ((n = fread(buf, sizeof(char)*2, 3, rfp)) > 0) { 20 fwrite(buf, sizeof(char)*2, n, wfp); 21 } 22 23 fclose(rfp); 24 fclose(wfp); 25 26 return 0; 27 } 항목크기가 char 크기의 2 배, 이것을 3 개, 즉 2*3=6 바이트씩읽어서출력 # ex2_14.out # cat unix.out Unix System Programming Unix System Programming Unix System Programming 43

형식기반입출력 형식기반입력함수 : scanf(3), fscanf(3) #include <stdio.h> int scanf(const char *restrict format,...); int fscanf(file *restrict stream, const char *restrict format,..); fscanf 도 scanf 가사용하는형식지정방법을그대로사용 성공하면읽어온항목의개수를리턴 형식기반출력함수 : printf(3), fprintf(3) #include <stdio.h> int printf(const char *restrict format, /* args */...); int fprintf(file *restrict stream, const char *restrict format, /*args */..)/ fprintf 는지정한파일로형식지정방법을사용하여출력 44

[ 예제 2-15] fscanf 함수사용하기 01 #include <stdlib.h> 02 #include <stdio.h> 03 04 int main(void) { 05 FILE *rfp; 06 int id, s1, s2, s3, s4, n; 07 08 if ((rfp = fopen("unix.dat", "r")) == NULL) { 09 perror("fopen: unix.dat"); 10 exit(1); 11 } 12 13 printf(" 학번평균 \n"); 14 while ((n=fscanf(rfp, "%d %d %d %d %d", &id,&s1,&s2,&s3,&s4))!= EOF) { 15 printf("%d : %d\n", id, (s1+s2+s3+s4)/4); 16 } 17 18 fclose(rfp); 19 20 return 0; 21 } # cat unix.dat 2009001 80 95 80 95 2009002 85 90 90 80 # ex2_15.out 학번평균 2009001 : 87 2009002 : 86 45

[ 예제 2-16] fprintf 함수사용하기 01 #include <stdlib.h> 02 #include <stdio.h> 03 04 int main(void) { 05 FILE *rfp, *wfp; 06 int id, s1, s2, s3, s4, n; 07 08 if ((rfp = fopen("unix.dat", "r")) == NULL) { 09 perror("fopen: unix.dat"); 10 exit(1); 11 } 12 13 if ((wfp = fopen("unix.scr", "w")) == NULL) { 14 perror("fopen: unix.scr"); 15 exit(1); 16 } 17 18 fprintf(wfp, " 학번 평균 \n"); 19 while ((n=fscanf(rfp, "%d %d %d %d %d", &id,&s1,&s2,&s3,&s4))!= EOF) { 20 fprintf(wfp, "%d : %d\n", id, (s1+s2+s3+s4)/4); 21 } 22 23 fclose(rfp); 24 fclose(wfp); 25 26 return 0; 27 } # cat unix.dat 2009001 80 95 80 95 2009002 85 90 90 80 입출력에형식지정기호사용 # ex2_16.out # cat unix.scr 학번평균 2009001 : 87 2009002 : 86 46

파일오프셋지정 [1] 파일오프셋이동 : fseek(3) #include <stdio.h> int fseek(file *stream, long offset, int whence); stream 이가리키는파일에서 offset 에지정한크기만큼오프셋을이동 whence 는 lseek 와같은값을사용 fseek 는성공하면 0 을실패하면 EOF 를리턴 현재오프셋구하기 : ftell(3) #include <stdio.h> long ftell(file *stream); 현재오프셋을리턴 오프셋은파일의시작에서현재위치까지의바이트수 47

파일오프셋지정 [2] 처음위치로오프셋이동 : rewind(3) #include <stdio.h> void rewind(file *stream); 오프셋을파일의시작위치로즉시이동 오프셋의저장과이동 : fsetpos(3), fgetpos(3) #include <stdio.h> int fsetpos(file *stream, const fpos_t *pos); int fgetpos(file *stream, fpos_t *pos); fgetpos : 파일의현재오프셋을 pos 가가리키는영역에저장 fsetpos : pos 가가리키는위치로파일오프셋을이동 48

[ 예제 2-17] fseek 함수사용하기... 04 int main(void) { 05 FILE *fp; 06 int n; 07 long cur; 08 char buf[bufsiz]; 09 10 if ((fp = fopen("unix.txt", "r")) == NULL) { 11 perror("fopen: unix.txt"); 12 exit(1); 13 } 14 현재오프셋읽기 15 cur = ftell(fp); 16 printf("offset cur=%d\n", (int)cur); 17 18 n = fread(buf, sizeof(char), 4, fp); 19 buf[n] = '\0'; 20 printf("-- Read Str=%s\n", buf); 21 22 fseek(fp, 1, SEEK_CUR); 23 24 cur = ftell(fp); 25 printf("offset cur=%d\n", (int)cur); 26 오프셋이동 49

[ 예제 2-17] fseek 함수사용하기 27 n = fread(buf, sizeof(char), 6, fp); 28 buf[n] = '\0'; 29 printf("-- Read Str=%s\n", buf); 30 31 cur = 12; 32 fsetpos(fp, &cur); 33 34 fgetpos(fp, &cur); 35 printf("offset cur=%d\n", (int)cur); 36 37 n = fread(buf, sizeof(char), 13, fp); 38 buf[n] = '\0'; 39 printf("-- Read Str=%s\n", buf); 40 41 fclose(fp); 42 43 return 0; 44 } 오프셋이동 현재오프셋읽어서지정 # ex2_17.out Offset cur=0 -- Read Str=Unix Offset cur=5 -- Read Str=System Offset cur=12 -- Read Str=Programming 50

파일기술자와파일포인터간변환 저수준파일입출력의파일기술자와고수준파일입출력의파일포인터는상호변환가능 파일포인터생성 : fdopen(3) #include <stdio.h> FILE *fdopen(int fildes, const char *mode); 파일기술자와모드값을받아파일포인터를생성 파일기술자생성 : fileno(3) #include <stdio.h> int fileno(file *stream); 파일포인터를인자로받아파일기술자를리턴 51

[ 예제 2-18] fdopen 함수사용하기 01 #include <fcntl.h> 02 #include <stdlib.h> 03 #include <stdio.h> 04 05 int main(void) { 06 FILE *fp; 07 int fd; 08 char str[bufsiz]; 09 10 fd = open("unix.txt", O_RDONLY); 11 if (fd == -1) { 12 perror("open"); 13 exit(1); 14 } 15 16 fp = fdopen(fd, "r"); 17 18 fgets(str, BUFSIZ, fp); 19 printf("read : %s\n", str); 20 21 fclose(fp); 22 23 return 0; 24 } 파일포인터생성 저수준파일입출력함수로파일오픈 고수준파일읽기함수로읽기 # ex2_18.out Read : Unix System Programming 52

[ 예제 2-19] fileno 함수사용하기 01 #include <unistd.h> 02 #include <fcntl.h> 03 #include <stdlib.h> 04 #include <stdio.h> 05 06 int main(void) { 07 FILE *fp; 08 int fd, n; 09 char str[bufsiz]; 10 11 fp = fopen("unix.txt", "r"); 12 if (fp == NULL) { 13 perror("fopen"); 14 exit(1); 15 } 16 17 fd = fileno(fp); 18 printf("fd : %d\n", fd); 19 20 n = read(fd, str, BUFSIZ); 21 str[n] = '\0'; 22 printf("read : %s\n", str);22 23 24 close(fd); 25 26 return 0; 27 } 고수준파일입출력함수로파일오픈 파일기술자리턴 저수준파일읽기함수로읽기 # ex2_19.out fd : 3 Read : Unix System Programming 53

요약 파일 파일은관련있는데이터들의집합으로하드디스크같은저장장치에일정한형태로저장 유닉스에서파일은데이터를저장하기위해서뿐만아니라데이터를전송하거나장치에접근하기위해서도사용 저수준파일입출력과고수준파일입출력 저수준파일입출력 : 유닉스커널의시스템호출을사용하여파일입출력을실행하며, 특수파일도읽고쓸수있음 고수준파일입출력 : 표준입출력라이브러리로다양한형태의파일입출력함수를제공 58