Linux ProgrammingSpring 2009
File Handling
Kongju National University
Important contents
Linux 에서 C 컴파일 방법 File 처리 프로그래밍 Linux 환경 접근 프로그래밍
Kongju National University Linux System Programming 2/29
Kongju National University
Basic compiling method
Linux C Compiler : gcc, cc 기본 :
Object file option
Compiler 도움말
% gcc –o hello.c
% ./a.out
% gcc –o hello hello.c
% ./hello
% man gcc
% info gcc : 추가정보
Kongju National University Linux System Programming 3/29
Kongju National University
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 4/29
Kongju National University
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 5/29
Kongju National University
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 6/29
Kongju National University
System Calls
System calls 일반적으로 사용자 프로그램은 운영체제 직접 관여 금지 Kernel 을 직접 통한 접근 금지 System call 에 의하여 운영체제 자체 인터페이스로 접근 저수준의 함수호출
Linux System Programming
Kongju National University
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 8/29
Kongju National University
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>
main()
{
if ((write(1,"Here is some data\n",18)) != 18)
write(2,"A write error has occurred on file decriptor 1\n",47);
}
Kongju National University Linux System Programming 9/29
Kongju National University
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>
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);}
Kongju National University Linux System Programming 10/29
Kongju National University
read testing
$echo hello there | simple_read hello there $ simple_read < test.txt …..
Kongju National University Linux System Programming 11/29
Kongju National University
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 12/29
Kongju National University
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 13/29
Kongju National University
close ()
파일 / 디바이스 닫기
return : 0( 성공 ), -1( 실패 )
#include <unistd.h>
int close(int fildes);
Kongju National University Linux System Programming 14/29
Kongju National University
저수준함수 파일복사 1 byte
#include <unistd.h> #include <sys/stat.h> #include <fcntl.h>
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);
}
Kongju National University Linux System Programming 15/29
Kongju National University
저수준 함수를 이용한 파일복사 1024bytes
#include <unistd.h> #include <sys/stat.h> #include <fcntl.h>
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);
}
Kongju National University Linux System Programming 16/29
Kongju National University
Exercise : file copy(1 char)
#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>
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);
}
Kongju National University Linux System Programming 17/29
Kongju National University
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 18/29
Kongju National University
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 19/29
Kongju National University
continued !
dup & dup2
파일을 접근하는 두개이상의 descriptor 생성하나의 파일에 대하여 두개의 접근이 가능토록
#include <unistd.h>
int dup(int fildes);
: return value 는 새로운 file descriptorint dup2(int fildes, int fildes2);
: fildes2 에 복제
Kongju National University Linux System Programming 20/29
Kongju National University
Programming Exercise
Programming Exercise 1
Read from open file with 1024 bytes reading(1 block)
1. declare char buf[1024]
2. 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 21/29
Kongju National University
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 22/29
Kongju National University
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 23/29
Kongju National University
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 24/29
Kongju National University
fgetc() , getc() : 단일문자 입력
#include <stdio.h>
FILE *input;char inputchar;
input=fopen(“date.in”,”r”);…inputchar=fgetc(input);…fclose(input);…
#include <stdio.h>int fgetc(FILE *stream);int getc(FILE *stream); macro 로 사용
Kongju National University Linux System Programming 25/29
Kongju National University
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 26/29
Kongju National University
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 27/29
Kongju National University
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 28/29
Kongju National University
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 29/29
Kongju National University
Ex: Grading
#include <stdio.h>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 30/29