Presentation is loading. Please wait.

Presentation is loading. Please wait.

FILE I/O 번째주 Dept. of Computer Science & Engineering

Similar presentations


Presentation on theme: "FILE I/O 번째주 Dept. of Computer Science & Engineering"— Presentation transcript:

1 FILE I/O - 1 3 번째주 Dept. of Computer Science & Engineering
Knowledge & Data Engineering Lab

2 File Operations create write read reposition within file delete
file seek delete truncate open() search the directory structure on disk for entry Fi, and move the content of entry to memory. close () move the content of entry Fi in memory to directory structure on disk.

3 System Call - open 사용법 #include <sys/types.h>
#include <sys/stat.h> #include <fcntl.h> int open (const char *pathname, int flag, [mode_t mode ]; 사용법 Return value – [성공시 : new file descriptor ] [실패시 :- 1] Flag <fcntl.h> O_RDONLY 읽기 전용 O_WRONLY 쓰기 전용 O_RDWR 읽기 쓰기 O_CREAT 파일이 존재 하지 않으면 생성 O_EXCL O_CREAT와 함꼐 사용되며 파일이 존재시 에러처리 O_TRUNC 파일이 존재시 잘라버림 O_APPEND 파일의 뒷부분에 추가

4 Open - example #include <stdlib.h> #include <fcntl.h>
char *workfile = “junk”; main() { int filedes; /* <fcntl.h>에 정의된 O_RDWR을 사용하여 개방한다 */ /* 파일을 읽기/쓰기로 개방한다 */ if ((ifledse = open (workfile, O_RDWR)) == -1) printf (“Couldn’t open %s\n”, workfile); exit(1); /* 오류이므로 퇴장한다 */ } /* 프로그램의 나머지 부분 */ exit(0); /* 정상적인 퇴장 */

5 System Call - create 사용법 #include <sys/types.h>
#include <sys/stat.h> #include <fcntl.h> int creat(const char *pathname, mode_t mode); 사용법 : 새파일 생성시 사용 : open 에서 O_CREAT|O_WRONLY|O_TRUNC flag와 같음

6 System Call - close 사용법 #include <sys/types.h>
#include <sys/stat.h> #include <fcntl.h> int close(const char *pathname, mode_t mode); 사용법 : 파일 사용을 끝냈음을 시스템에게 알림 Return value - [성공시 : 0] [실패시 : -1]

7 System Call - read 사용법 #include <unistd.h>
ssize_t read(int fd, void *buf, size_t count); 사용법 Return value – [성공시 : number of bytes read] [End of file : 0] [실패시 :- 1] : 파일로 부터 임의의 byte를 버퍼로 복사하는데 사용

8 System Call - write 사용법 #include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count); 사용법 Return value – [성공시 : number of bytes read] [End of file : 0] [실패시 :- 1] : 버퍼로부터 임의의 byte를 파일에 쓰는데 사용

9 Example : Simple File I/O
#include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #define BSIZE 1024 #define FPERM 0644 int main(int argc, char *argv[]) { int fd1, fd2, n; char buf[BSIZE]; if (argc < 3) { fprintf(stderr, "Usage; %s src dest\n", argv[0]); exit(1); } if ((fd1 = open(argv[1], O_RDONLY)) < 0) { perror("file open error"); if ((fd2 = creat(argv[2], FPERM)) < 0) { perror("file creation error"); exit(1); } while ((n = read(fd1, buf, BSIZE)) > 0) /* assume no read/write error */ write(fd2, buf, n); close(fd1); close(fd2);

10 System Call - close 사용법 #include <sys/types.h>
#include <unistd.h> off_t lseek(int fd, off_t offset, int whence); 사용법 : 새파일 생성시 사용 : open 에서 O_CREAT|O_WRONLY|O_TRUNC flag와 같음

11 /* 한파일의 내용을 다른파일로 복사하는 함수 copyfile을 작성하여라*/ 첫번째파일을개방한다 두번째파일을생성한다
첫번째파일의끝에도달할때까지 첫번째파일을읽어두번째파일에쓴다 두파일을닫는다

12 Example (1/3) /* copyfile--name1을name2로복사한다*/
#include <unistd.h> #include <fcntl.h> #define BUFSIZE 512 /* 읽혀질덩어리의크기*/ #define PERM0644 /* 새파일의파일허가*/ // copyfile의main 함수, test.in파일이존재해야한다. main() { intretcode; retcode= copyfile("test.in", "test.out"); }

13 Example (2/3) /* name1을name2로복사한다*/
intcopyfile(const char *name1, const char *name2) { intinfile, outfile; ssize_tnread; char buffer[BUFSIZE]; if( (infile= open (name1, O_RDONLY) )== -1) return(-1); if( (outfile= open (name2,O_WRONLY | O_CREAT | O_TRUNC, PERM))== -1) close (infile); return(-2); }

14 Example (3/3) /* 이제name1로부터한번에BUFSIZE 문자를읽는다*/
while ( (nread= read (infile, buffer, BUFSIZE) ) > 0) { /* buffer를출력파일에쓴다. */ if ( write(outfile, buffer, nread) < nread) { close (infile); close (outfile); return (-3);/* 쓰기오류*/ } if (nread== -1) return (-4);/* 마지막일기에서오류발생*/ else return (0);/* 만사가잘되었음*/

15 System Call - lseek 사용법 #include <sys/types.h>
#include <unistd.h> off_t lseek(int fd, off_t offset, int whence); 사용법 : 열린 파일의 읽기/쓰기 위치를 옮긴다 : offset : file pointer를상대적으로이동할바이트수 - 양수: 뒤로, 음수: 앞으로 : start_flag - SEEK_SET : 처음에서 - SEEK_CUR : 현재위치에서 - SEEK_END : 끝에서 : Return value - 성공시: file pointer의새로운위치(절대위치) - 실패시: -1

16 System Call – lseek (cont’d)
기존파일의끝에추가하기 filedes= open(filename,O_RDWR); lseek(filedes, (off_t)0, SEEK_END); write(filedes, outbuf, OBSIZE); 파일의크기를알아볼때 off_tfilesize; intfiledes; filesize= lseek(filedes, (off_t)0, SEEK_END); 한파일의끝에자료를추가하기 1) lseek(filedes, (off_t)0, SEEK_END); write(filedes, appbuf, BUFSIZE); 2) filedes= open(“yetanother”, O_WRONLY | O_APPEND); -> 4page

17 Example #2: lseek (1) #include <stdio.h>
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> char buf1[] = "abcdefghij"; char buf2[] = "ABCDEFGHIJ"; int main(void) { int fd; if ((fd = creat("file.hole", 0640)) < 0) { perror("creat error"); exit(1); }

18 Example #2: lseek (2) if (write(fd, buf1, 10) != 10) {
perror("buf1 write error"); exit(1); } /* offset now = 10 */ if (lseek(fd, 40, SEEK_SET) == -1) { perror("lseek error"); /* offset now = 40 */ if (write(fd, buf2, 10) != 10) { perror("buf2 write error"); /* offset now = 50 */ exit(0);

19 System Call – ulink/remove
#include <unistd.h> intunlink(constchar *pathname); #include <stdio.h> intremove(constchar *pathname); 사용법 unlink/remove : 파일을제거한다 – pathname: 절대적혹은상대적파일/디렉토리경로명 – Return value [성공시: 0] [실패시: -1] – 빈디렉토리를제거할때는remove만을사용한다

20 System Call – fcntl 사용법 #include <sys/types.h>
#include <unistd.h> #include <fcntl.h> int fcntl(int fd, int cmd, ...); 사용법 fcntl: 열린파일의속성(attribute)을제어한다 – fd: open 혹은creat이반환한파일descriptor –층 F_GETFL : flag를통한파일상태표시기를되돌려준다 F_SETFL : 파일상태표시기를세번째변수의값으로정한다 – O_APPEND, O_NONBLOCK, O_SYNC, O_ASYNC 만가능 – Return value [성공시: 자연수(>=0)] – F_GETFL사용시는(반환값&O_ACCMODE)가open의flag임 [실패시: -1] – F_SETFL사용시는0#

21 Example fcntl (1/2) #include <stdio.h>
#include <sys/types.h> #include <fcntl.h> int main(intargc, char *argv[]) { int accmode, val; if (argc!= 2) { fprintf(stderr, "usage: a.out<descriptor#>"); exit(1); } if ((val= fcntl(atoi(argv[1]), F_GETFL, 0)) < 0) { perror("fcntlerror for fd"); accmode= val& O_ACCMODE;

22 Example fcntl (2/2) if (accmode== O_RDONLY) printf("readonly");
else if (accmode== O_WRONLY) printf("writeonly"); else if (accmode== O_RDWR) printf("readwrite"); else {fprintf(stderr, "unkownaccess mode"); exit(1); } if (val& O_APPEND) printf(", append"); if (val& O_NONBLOCK) printf(", nonblocking"); if (val& O_SYNC) printf(", syschronouswrites"); putchar('\n'); exit(0);

23 errno & perror 파일접근system call 실패시: -1 return errno perror서브루틴
오류변수, <errno.h>에포함 system call 동안발생했던오류의마지막type 기록 perror서브루틴 문자열인수, 콜론, errno변수의현재값의메시지를출력 perror(“erroropening nonesuch”); 만일nonesuch가존재하지않으면 error opening nonesuch: No such file or directory 출력


Download ppt "FILE I/O 번째주 Dept. of Computer Science & Engineering"

Similar presentations


Ads by Google