유닉스(Unix)/시스템 프로그래밍
저수준 파일 입출력
ddingz
2021. 8. 15. 11:14
파일 기술자
모든 저수준 파일 입출력 함수는 파일 기술자file descriptor를 사용한다.
파일 기술자는 현재 열려 있는 파일을 구분할 목적으로 유닉스가 붙여놓은 번호로, 저수준 파일 입출력에서 열린 파일을 참조하는 데 사용하는 지시자 역할을 한다.
파일 기술자는 정수값으로, open 함수를 사용해 파일을 열었을 때 부여된다.
파일 생성과 열고 닫기
파일 열기 : open(2)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *path, int oflag [, mode_t mode]);
// path : 열려는 파일이 있는 경로, mode : 접근 권한, oflag : 파일 상태 플래그
파일 생성 : creat(2)
#include <sys/stat.h>
#inlcude <fcntl.h>
int creat(const char *path, mode_t mode);
// path : 파일을 생성할 경로, mode : 접근 권한
파일 닫기 : close(2)
#include <unistd.h>
int close(int fildes);
// fildes : 파일 기술자
파일 읽기와 쓰기
파일 읽기 : read(2)
#include <unistd.h>
ssize_t read(int fildes, void *buf, size_t nbytes);
// fildes : 파일 기술자, buf : 바이트를 저장할 메모리 영역의 시작 주소, nbytes : 읽어올 바이트 수
파일 쓰기 : write(2)
#include <unistd.h>
ssize_t write(int fildes, const void *buf, size_t nbytes);
// fildes : 파일 기술자, buf : 파일에 기록할 데이터를 저장한 메모리 영역, nbytes : buf의 크기(기록할 데이터의 크기)
파일 오프셋 지정
파일 오프셋 위치 지정 : lseek(2)
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fildes, off_t offset, int whence);
// fildes : 파일 기술자, offset : 이동할 오프셋 위치, whence : 오프셋의 기준 위치
파일 기술자 복사
파일 기술자 복사하기 : dup(2)
#include <unistd.h>
int dup(int fildes);
// fildes : 파일 기술자
파일 기술자 복사 : dup2(3)
#include <unistd.h>
int dup2(int fildes, int fildes2);
// fildes : 파일 기술자, fildes2 : 파일 기술자를 복사할 곳
파일 기술자 제어
파일 기술자 제어 : fcntl(2)
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fildes, int cmd, /* arg */ ...);
// fildes : 파일 기술자, cmd : 명령, arg : cmd에 따라 필요시 지정하는 인자들
파일 삭제
파일 삭제 : unlink(2)
#include <unistd.h>
int unlink(const char *path);
// path : 삭제할 파일의 경로
파일 삭제 : remove(3)
#include <stdio.h>
int remove(const char *path);
// path : 경로
파일과 디스크 동기화 함수
파일과 디스크 동기화 함수 : fsync(3)
#include <unistd.h>
int fsync(int fildes);
// fildes : 파일 기술자