Linux Programming Spring 2008 File Handling
Linux System Programming Important contents Linux 에서 C 컴파일 방법 File 처리 프로그래밍 Linux 환경 접근 프로그래밍 Kongju National University Linux System Programming
Basic compiling method Linux C Compiler : gcc, cc 기본 : Object file option Compiler 도움말 % gcc hello.c % ./a.out % gcc –o hello hello.c % ./hello % man gcc % info gcc : 추가정보 Kongju National University Linux System Programming
Linux System Programming Header file Header file 위치 /usr/include/ 아래에 위치 Cf: /usr/include/[sys, linux, X11, g++-2] Header file including % gcc –I/usr/openwin/include fred.c 프로그램 내 Header file including #include <stdio.h> Kongju National University Linux System Programming
Linux System Programming Library Linking 재사용 가능, 공통사용, 미리 컴파일된 함수 위치 : /lib /usr/lib 분류 : 정적 라이브러리 : .a 공유 라이브러리 : .so, .sa Linking방법(default lib directory) Linking방법(other lib directory) % gcc –o fred fred.c /usr/lib/libm.a % gcc –o fred fred.c -lm % gcc –o xfred –L/usr/openwin/lib xfred.c -Lx11 Kongju National University Linux System Programming
Library Linking (static lib) 정적라이브러리(static lib) : .a Linking at compile time 메모리 자원 낭비 동적라이브러리(dynamic lib) : …so.N N:번호 확인방법 : % ldd objectfile compile 방법 lib 생성방법 % gcc –c bill.c fred.c % ls *.o bill.o fred.o % gcc –c mainpgm.c % gcc –o runpgm mainpgm.o bill.o % ./runpgm % ar crv libfoo.a bill.o fred.c ac – bill.o ac - fred.o % ranlib libfoo.a :BSD계열에서 % gcc –o runpgm mainpgm.o libfoo.a % ./runpgm Kongju National University Linux System Programming
Linux System Programming System Calls System calls 일반적으로 사용자 프로그램은 운영체제 직접 관여 금지 Kernel을 직접 통한 접근 금지 System call에 의하여 운영체제 자체 인터페이스로 접근 저수준의 함수호출 Linux System Programming
File Handling Programming Everything is FILE in Linux & Unix File property 이름,생성/변경날짜, 허용권한,길이,inode정보 Low level file handling system call /dev 아래의 모든 device에 동일한 방법 적용 주요 system calls open(), read(), write() : close(), ioctl() File I/O descriptor 0 (표준입력), 1 (표준출력), 3 (표준에러) Kongju National University Linux System Programming
Linux System Programming write() 열린 파일이나 디바이스에 쓰기 return=nbytes, 0=fail to write, -1=fail to call #include <unistd.h> Size_t write(int fildes,void *buf,size_t nbytes); #include <unistd.h> int main() { if ((write(1,"Here is some data\n",18)) != 18) write(2,"A write error has occurred on file decriptor 1\n",47); exit(0); } Kongju National University Linux System Programming
Linux System Programming read () 열린 파일/디바이스로 부터 읽기 return=nbytes, 0=fail to write, -1=fail to call #include <unistd.h> Size_t read(int fildes,void *buf,size_t nbytes); #include <unistd.h> int main() { char buffer[120]; int nread; nread = read(0, buffer, 128); if (nread == -1) write(2, "A read error has occurred\n", 26); if ((write(1,buffer,nread)) != nread) write(2, "A write error has occurred\n",27); exit(0); } Kongju National University Linux System Programming
Linux System Programming read testing $echo hello there | simple_read hello there $ simple_read < test.txt ….. Kongju National University Linux System Programming
Linux System Programming open() 파일/디바이스 열기 return : >0(성공), -1(실패, errno:실패원인) oflags : #include <fcntl.h> #include <sys/types.h> : POSIX에서 불필요 #include <sys/stat.h> : POSIX에서 불필요 int open(const char *path, int oflags); int open(const char *path, int oflags, mode_t mode); O_RDONLY : 읽기 전용상태로 연다 O_WRONLY : 쓰기 전용상태로 연다 O_RDWR : 읽기와 쓰기가 가능한 상태로 연다 그외 oflags의 비트조합으로 사용 가능 O_APPEND, O_TRUNC(기존내용제거후), O_CREAT(필요시생성), O_EXCL(O_CREAT와 함께,배타적사용) Kongju National University Linux System Programming
Linux System Programming open() mode_t S_IRUSR,S_IWUSR,S_IXUSR : 사용자 읽기,쓰기,실행 S_IRGRP,S_IWGRP,S_IXGRP : 그룹 읽기,쓰기,실행 S_IROTH,S_IWOTH,S_IXOTH : 기타사용자 읽기,쓰기,실행 open(“myfile”,O_CREAT, S_IRUSR|S_IXOTH); Kongju National University Linux System Programming
Linux System Programming close () 파일/디바이스 닫기 return : 0(성공), -1(실패) #include <unistd.h> int close(int fildes); Kongju National University Linux System Programming
Linux System Programming 저수준함수 파일복사 1 byte #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> int main() { char c; int in, out; in = open("file.in", O_RDONLY); out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); while(read(in,&c,1)) > 0) write(out,&c,1); exit(0); } Kongju National University Linux System Programming
Linux System Programming 저수준 함수를 이용한 파일복사 1024bytes #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> int main() { char block[1024]; int in, out; int nread; in = open("file.in", O_RDONLY); out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); while((nread = read(in,block,sizeof(block))) > 0) write(out,block,nread); exit(0); } Kongju National University Linux System Programming
Exercise : file copy(1 char) #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> int main() { char c; int in, out; in = open("file.in", O_RDONLY); out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); while(read(in, &c, 1) == 1) write(out, &c, 1); exit(0); } Kongju National University Linux System Programming
File management system calls 파일 사용방법 제어, 상태정보 파악 주요 system calls lseek #include <unistd.h> #include <sys/types.h> off_t lseek(int fildes, off_t offset, int whence); whence : SEEK_SET : 절대 offset 위치 SEEK_CUR : 현재위치에서 상대위치 SEEK_END : 파일의 마지막에 위치 Kongju National University Linux System Programming
Linux System Programming continued! fstat, stat & lstat File descriptor관 관련된 파일의 상태 정보 파악 #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int fstat(int fildes, struct stat *buf); int stat(const char *path, struct stat *buf); :link가 참조하는 파일 정보 int lstat(const char *path, struct stat *buf); :symbolic link 자체 정보 * 자세한 사항은 필요시 %man fstat Kongju National University Linux System Programming
Linux System Programming continued ! dup & dup2 파일을 접근하는 두개이상의 descriptor생성 하나의 파일에 대하여 두개의 접근이 가능토록 #include <unistd.h> int dup(int fildes); : return value는 새로운 file descriptor int dup2(int fildes, int fildes2); : fildes2에 복제 Kongju National University Linux System Programming
Linux System Programming Programming Exercise Programming Exercise 1 Read from open file with 1024 bytes reading(1 block) declare char buf[1024] in while loop, condition should be changed read(…,buf,size..) Programming Exercise 2 touch 명령어와 유사한 기능, 단 파라메터로 파일 permission mode줄 수 있도록 Ex: mytouch –r –w –r Programming Exercise 3 cp 명령어와 유사한 기능, 단 파일만 copy Due date : next week, uploading methods will be provided Kongju National University Linux System Programming
Linux System Programming Standard I/O library Low level I/O 의 불편함 해소 공통적인 라이브러리 제공 Head file : stdio.h 주요 function calls fopen, fclose fread, fwrite fflush, fseek fgetc, getc, getchar fputc, putc, putchar printf, fprintf, sprintf scanf, fscanf, sscanf Kongju National University Linux System Programming
Linux System Programming fopen(), fclose() #include <stdio.h> FILE *fopen(const char *filename,const char *mode); mode : “r”, “w”, “a” “r+”, “w+”, “a+” : + =갱신상태로 int fclose(FILE *stream) } Kongju National University Linux System Programming
Linux System Programming Ex : File copy #include <stdio.h> main(int argc, char *argv[]) { FILE *infile, *outfile; char buf[256]; if(argc !=3) { printf(“ERROR : parameter mismatch\n”); return;} infile=fopen(argv[1],”r”); outfile=fopen(argv[2],”w”); while(fgets(buf,256,infile)!=NULL){ fprinf(outfile,”%s”,buf); } fclose(infile);fclose(outfile); return; Kongju National University Linux System Programming
fgetc() , getc() :단일문자 입력 #include <stdio.h> int fgetc(FILE *stream); int getc(FILE *stream); macro로 사용 #include <stdio.h> FILE *input; char inputchar; input=fopen(“date.in”,”r”); … inputchar=fgetc(input); fclose(input); Kongju National University Linux System Programming
Linux System Programming fputc(), putc() #include <stdio.h> int fputc(int c, FILE *stream); int putc(int c, FILE *stream); macro로 사용 주의: c는 unsigned char #include <stdio.h> FILE *input,*output; char inputchar; input=fopen(“date.in”,”r”); output=fopen(“data.out”,”w”); while((inputchar=fgetc(input))!=EOF) { fputc(inputchar,output); } …… fclose(input); fclose(output); … Kongju National University Linux System Programming
Linux System Programming fgets(), gets() :문자열 입력 #include <stdio.h> int fgets(char *s,int n, FILE *stream); int *gets(char *s); macro로 사용 #include <stdio.h> FILE *input; int maxlen=100; char inputstring[maxlen]; input=fopen(“date.in”,”r”); fgets(inputstring,maxlen,input); …… fclose(input); … Kongju National University Linux System Programming
Linux System Programming fputs(), puts() :문자열 출력 #include <stdio.h> int fputs(char *s, FILE *stream); int *puts(const char *s); macro로 사용 #include <stdio.h> FILE *input,*output; int maxlen=126; char instring; input=fopen(“date.in”,”r”); output=fopen(“data.out”,”w”); while((fgets(instring,maxlen,input)!=NULL ) { fputs(instring,output); } …… fclose(input); fclose(output); … Kongju National University Linux System Programming
fscanf(), fprintf() :형식화된 입출력 #include <stdio.h> int fscanf(FILE *stream, const char *format, argument….); int fprintf(FILE *stream, const char *format, argument….); Kongju National University Linux System Programming
Linux System Programming Ex: Grading #include <stdio.h> void main() { FILE *infile, *outfile; char name[20]; int kor,mat, eng, tot; if((infile=fopen("data.in","r"))== NULL) { printf("ERROR: cannot open file data.in\n"); } if((outfile=fopen("data.out","w"))== NULL) { printf("ERROR: cannot open file data.out\n");} while(fscanf(infile,"%s%d%d%d",name,&kor,&mat,&eng) !=EOF){ tot=kor+mat+eng; fprintf(outfile,"%-8s%3d%5d%5d%5d\n",name,kor,mat,eng,tot); } fclose(infile); fclose(outfile); Kongju National University Linux System Programming