동캄의 코딩도장

FILE I/O [2] 본문

CS/시스템프로그래밍

FILE I/O [2]

동 캄 2022. 2. 4. 22:42

파일 읽기/쓰기 (File read and write)

Reading a fiel - read(2)

ex)
#include <unistd.h>

ssize_t read ( int fd, void *buf , size_t count);

fd (file descriptor)
- 읽으려는 파일의 file descriptor

buf (buffer)
- 읽은 내용을 저장할 buffer의 시작 주소

count
- 읽을 byte의 수

Return: 실제로 읽은 byte의 수( 0: 파일 끝에 도달, -1: 에러)

Writing to a file - write (2)

#include <unistd.h>

ssize_t write (int fd, const void *buf, size_t count);

fd (file descriptor)
- 기록하려는 파일의 file descriptor

buf (buffer)
- 기록할 내용이 저장된 buffer의 시작 주소

count
- 기록할 byte의 수

Return: 실제로 기록한 byte의 수 (-1: 에러)

File offset (File position)
- File operation (e.g.. read/write)을 적용할 위치
- 파일의 시작점부터 현재 위치까지의 byte 수

-Read(2)/Write(2) 수행 시, 읽은/기록한 byte 수 만큼 순차적으로 이동

File access methods
- Sequential access (순차 접근) : File을 record (or bytes) 단위로 순서대로 접근 ex) fgetc()
- Directed accesss (직접 접근) : 원하는 Block 을 직접접근 ex0 lseek(), seek()

Moving the file offset - lseek (2)

#include <sys/types.h>
#include <unistd.h>

off_t lseek (int fd, off_t offset, int whence);

fd (file descriptor)
- 대상 file descriptor

offset
- 이동시킬 byte 수 (양수 or 음수)

whence
- 기준위치
- SEEK_SET: 파일의 시작
- SEEK_CUR: 현재 위치
- SEEK_END: 파일의 끝
- ex) lseek (fd, 5, SEEK_SET) -> 파일 시작에서 5번째 byte로 이동
      cur_offset = lseek(fd,0,SEEK_CUR)

Return : 이동 후 file offset (-1:에러)

Page cache
- In-memory store of recently accessed data from an on-disk filesystem
- Disk 접근 시간 절약을 위해 kernel 내부적 기법

page write-back
- Page cache에 변경 된 내용을 disk에 반영하는 것
- 반영 시기는 kernel이 결정

Synchronizing with disks - fsync(2)

#include <unistd.h>
int fsync (int fd);

page write-back을 강제로 수행

fd(file descriptor)
대상: file descriptor

Return ( 0:success, -1:error)

'CS > 시스템프로그래밍' 카테고리의 다른 글

DISK I/O [1]  (0) 2022.02.04
FILE I/O [3]  (0) 2022.02.04
FILE I/O [1]  (0) 2022.02.04
파일 개요& 기본 명령어  (0) 2022.02.04
Makefile & make  (0) 2022.02.04