Liux Programmig Sprig 2008 File Hadlig
Importat cotets Liux 에서 C 컴파일방법 File 처리프로그래밍 Liux 환경접근프로그래밍 Kogju Natioal Uiversity Liux System Programmig 2/29
Basic compilig method Liux C Compiler : gcc, cc 기본 : % gcc o hello.c %./a.out Object file optio % gcc o hello hello.c %./hello Compiler 도움말 % ma gcc % ifo gcc : 추가정보 Kogju Natioal Uiversity Liux System Programmig 3/29
Header file Header file 위치 /usr/iclude/ 아래에위치 Cf: /usr/iclude/[sys, liux, X11, g++-2] Header file icludig % gcc I/usr/opewi/iclude fred.c 프로그램내 Header file icludig #iclude <stdio.h> Kogju Natioal Uiversity Liux System Programmig 4/29
Library Likig 재사용가능, 공통사용, 미리컴파일된함수위치 : /lib /usr/lib 분류 : 정적라이브러리 :.a 공유라이브러리 :.so,.sa Likig 방법 (default lib directory) % gcc o fred fred.c /usr/lib/libm.a % gcc o fred fred.c -lm Likig 방법 (other lib directory) % gcc o xfred L/usr/opewi/lib xfred.c -Lx11 Kogju Natioal Uiversity Liux System Programmig 5/29
Library Likig (static lib) 정적라이브러리 (static lib) :.a Likig at compile time 메모리자원낭비 동적라이브러리 (dyamic lib) : so.n N: 번호확인방법 : % ldd objectfile compile 방법 lib 생성방법 % gcc c bill.c fred.c % ls *.o bill.o fred.o % gcc c maipgm.c % gcc o rupgm maipgm.o bill.o %./rupgm % ar crv libfoo.a bill.o fred.c ac bill.o ac - fred.o % ralib libfoo.a :BSD 계열에서 % gcc o rupgm maipgm.o libfoo.a %./rupgm Kogju Natioal Uiversity Liux System Programmig 6/29
System Calls System calls 일반적으로사용자프로그램은운영체제직접관여금지 Kerel을직접통한접근금지 System call에의하여운영체제자체인터페이스로접근저수준의함수호출 Kogju Natioal Uiversity Liux System Programmig
File Hadlig Programmig Everythig is FILE i Liux & Uix File property 이름, 생성 / 변경날짜, 허용권한, 길이,iode 정보 Low level file hadlig system call /dev 아래의모든 device 에동일한방법적용 주요 system calls ope(), read(), write() : close(), ioctl() File I/O descriptor 0 ( 표준입력 ), 1 ( 표준출력 ), 3 ( 표준에러 ) Kogju Natioal Uiversity Liux System Programmig 8/29
write() 열린파일이나디바이스에쓰기 #iclude <uistd.h> Size_t write(it fildes,void *buf,size_t bytes); retur=bytes, 0=fail to write, -1=fail to call #iclude <uistd.h> mai() { if ((write(1,"here is some data\",18))!= 18) write(2,"a write error has occurred o file decriptor 1\",47); exit(0); } Kogju Natioal Uiversity Liux System Programmig 9/29
read () 열린파일 / 디바이스로부터읽기 #iclude <uistd.h> Size_t read(it fildes,void *buf,size_t bytes); retur=bytes, 0=fail to write, -1=fail to call #iclude <uistd.h> mai() { char buffer[120]; it read; read = read(0, buffer, 128); if (read == -1) write(2, "A read error has occurred\", 26); if ((write(1,buffer,read))!= read) write(2, "A write error has occurred\",27); exit(0); } Kogju Natioal Uiversity Liux System Programmig 10/29
read testig $echo hello there simple_read hello there $ simple_read < test.txt.. Kogju Natioal Uiversity Liux System Programmig 11/29
ope() 파일 / 디바이스열기 #iclude <fctl.h> #iclude <sys/types.h> : POSIX에서불필요 #iclude <sys/stat.h> : POSIX에서불필요 it ope(cost char *path, it oflags); it ope(cost char *path, it oflags, mode_t mode); retur : >0( 성공 ), -1( 실패, erro: 실패원인 ) oflags : O_RDONLY : 읽기전용상태로연다 O_WRONLY : 쓰기전용상태로연다 O_RDWR : 읽기와쓰기가가능한상태로연다그외 oflags의비트조합으로사용가능 O_APPEND, O_TRUNC( 기존내용제거후 ), O_CREAT( 필요시생성 ), O_EXCL(O_CREAT와함께, 배타적사용 ) Kogju Natioal Uiversity Liux System Programmig 12/29
ope() mode_t S_IRUSR,S_IWUSR,S_IXUSR : 사용자읽기, 쓰기, 실행 S_IRGRP,S_IWGRP,S_IXGRP : 그룹읽기, 쓰기, 실행 S_IROTH,S_IWOTH,S_IXOTH : 기타사용자읽기, 쓰기, 실행 ope( myfile,o_creat, S_IRUSR S_IXOTH); Kogju Natioal Uiversity Liux System Programmig 13/29
close () 파일 / 디바이스닫기 #iclude <uistd.h> it close(it fildes); retur : 0( 성공 ), -1( 실패 ) Kogju Natioal Uiversity Liux System Programmig 14/29
저수준함수파일복사 1 byte #iclude <uistd.h> #iclude <sys/stat.h> #iclude <fctl.h> { mai() char c; it i, out; i = ope("file.i", O_RDONLY); out = ope("file.out", O_WRONLY O_CREAT, S_IRUSR S_IWUSR); while(read(i,&c,1) > 0) write(out,&c,1); } exit(0); Kogju Natioal Uiversity Liux System Programmig 15/29
저수준함수를이용한파일복사 1024bytes #iclude <uistd.h> #iclude <sys/stat.h> #iclude <fctl.h> { mai() char block[1024]; it i, out; it read; i = ope("file.i", O_RDONLY); out = ope("file.out", O_WRONLY O_CREAT, S_IRUSR S_IWUSR); while((read = read(i,block,sizeof(block))) > 0) write(out,block,read); } exit(0); Kogju Natioal Uiversity Liux System Programmig 16/29
Exercise : file copy(1 char) #iclude <uistd.h> #iclude <sys/stat.h> #iclude <fctl.h> mai() { char c; it i, out; i = ope("file.i", O_RDONLY); out = ope("file.out", O_WRONLY O_CREAT, S_IRUSR S_IWUSR); while(read(i, &c, 1) == 1) write(out, &c, 1); } exit(0); Kogju Natioal Uiversity Liux System Programmig 17/29
File maagemet system calls 파일사용방법제어, 상태정보파악 주요 system calls lseek #iclude <uistd.h> #iclude <sys/types.h> off_t lseek(it fildes, off_t offset, it whece); whece : SEEK_SET : 절대 offset 위치 SEEK_CUR : 현재위치에서상대위치 SEEK_END : 파일의마지막에위치 Kogju Natioal Uiversity Liux System Programmig 18/29
cotiued! fstat, stat & lstat File descriptor 관관련된파일의상태정보파악 #iclude <uistd.h> #iclude <sys/stat.h> #iclude <sys/types.h> it fstat(it fildes, struct stat *buf); it stat(cost char *path, struct stat *buf); :lik 가참조하는파일정보 it lstat(cost char *path, struct stat *buf); :symbolic lik 자체정보 * 자세한사항은필요시 %ma fstat Kogju Natioal Uiversity Liux System Programmig 19/29
cotiued! dup & dup2 파일을접근하는두개이상의 descriptor 생성 하나의파일에대하여두개의접근이가능토록 #iclude <uistd.h> it dup(it fildes); : retur value 는새로운 file descriptor it dup2(it fildes, it fildes2); : fildes2 에복제 Kogju Natioal Uiversity Liux System Programmig 20/29
Programmig Exercise Programmig Exercise 1 Read from ope file with 1024 bytes readig(1 block) 1. declare char buf[1024] 2. i while loop, coditio should be chaged read(,buf,size..) Programmig Exercise 2 touch 명령어와유사한기능, 단파라메터로파일 permissio mode줄수있도록 Ex: mytouch r w r Programmig Exercise 3 cp 명령어와유사한기능, 단파일만 copy Due date : ext week, uploadig methods will be provided Kogju Natioal Uiversity Liux System Programmig 21/29
Stadard I/O library Low level I/O 의불편함해소공통적인라이브러리제공 Head file : stdio.h 주요 fuctio calls fope, fclose fread, fwrite fflush, fseek fgetc, getc, getchar fputc, putc, putchar pritf, fpritf, spritf scaf, fscaf, sscaf Kogju Natioal Uiversity Liux System Programmig 22/29
fope(), fclose() #iclude <stdio.h> FILE *fope(cost char *fileame,cost char *mode); mode : r, w, a r+, w+, a+ : + = 갱신상태로 it fclose(file *stream) } Kogju Natioal Uiversity Liux System Programmig 23/29
Ex : File copy #iclude <stdio.h> mai(it argc, char *argv[]) { FILE *ifile, *outfile; char buf[256]; if(argc!=3) { pritf( ERROR : parameter mismatch\ ); retur;} ifile=fope(argv[1], r ); outfile=fope(argv[2], w ); while(fgets(buf,256,ifile)!=null){ fprif(outfile, %s,buf); } fclose(ifile);fclose(outfile); retur; } Kogju Natioal Uiversity Liux System Programmig 24/29
fgetc(), getc() : 단일문자입력 #iclude <stdio.h> it fgetc(file *stream); it getc(file *stream); macro 로사용 #iclude <stdio.h> FILE *iput; char iputchar; iput=fope( date.i, r ); iputchar=fgetc(iput); fclose(iput); Kogju Natioal Uiversity Liux System Programmig 25/29
fputc(), putc() #iclude <stdio.h> it fputc(it c, FILE *stream); it putc(it c, FILE *stream); macro 로사용주의 : c 는 usiged char #iclude <stdio.h> FILE *iput,*output; char iputchar; iput=fope( date.i, r ); output=fope( data.out, w ); while((iputchar=fgetc(iput))!=eof) { fputc(iputchar,output); } fclose(iput); fclose(output); Kogju Natioal Uiversity Liux System Programmig 26/29
fgets(), gets() : 문자열입력 #iclude <stdio.h> it fgets(char *s,it, FILE *stream); it *gets(char *s); macro 로사용 #iclude <stdio.h> FILE *iput; it maxle=100; char iputstrig[maxle]; iput=fope( date.i, r ); fgets(iputstrig,maxle,iput); fclose(iput); Kogju Natioal Uiversity Liux System Programmig 27/29
fputs(), puts() : 문자열출력 #iclude <stdio.h> it fputs(char *s, FILE *stream); it *puts(cost char *s); macro 로사용 #iclude <stdio.h> FILE *iput,*output; it maxle=126; char istrig; iput=fope( date.i, r ); output=fope( data.out, w ); while((fgets(istrig,maxle,iput)!=null ) { fputs(istrig,output); } fclose(iput); fclose(output); Kogju Natioal Uiversity Liux System Programmig 28/29
fscaf(), fpritf() : 형식화된입출력 #iclude <stdio.h> it fscaf(file *stream, cost char *format, argumet.); it fpritf(file *stream, cost char *format, argumet.); Kogju Natioal Uiversity Liux System Programmig 29/29
Ex: Gradig #iclude <stdio.h> void mai() { FILE *ifile, *outfile; char ame[20]; it kor,mat, eg, tot; if((ifile=fope("data.i","r"))== NULL) { pritf("error: caot ope file data.i\"); } if((outfile=fope("data.out","w"))== NULL) { pritf("error: caot ope file data.out\");} while(fscaf(ifile,"%s%d%d%d",ame,&kor,&mat,&eg)!= EOF){ tot=kor+mat+eg; fpritf(outfile,"%- 8s%3d%5d%5d%5d\",ame,kor,mat,eg,tot); } fclose(ifile); fclose(outfile); } Kogju Natioal Uiversity Liux System Programmig 30/29