open()
- path가 나타내는 파일을 oflag 모드로 연다
- prototype
- oflag : 대상의 입출력 방식을 지정함
- O_RDONLY : 읽기 모드, read() 호출 가능
- O_WRONLY : 쓰기 모드, write() 호출 가능
- O_RDWR : 읽기/쓰기 모드, read()/write() 호출 가능
(여기까지 필수 지정/다음부터 선택 지정) - O_APPEND : 파일 끝에 데이터 첨부
- O_CREAT : 해당 파일이 없는 경우 파일 생성
mode는 생성할 파일의 사용권한을 나타낸다 - O_TRUNC : 해당 파일이 있는 경우 내용 삭제
- O_EXCL : O_CREAT와 함께 사용되며 해당 파일이 이미 있으면 에러 발생
- O_NONBLOCK : 넌블로킹모드로 입출력 하도록 함
- O_SYNC : write() 시스템 호출을 하면 디스크에 물리적으로 쓴 후 반환
- 파일 열기 예시
- fd = open("account", O_RDONLY);
- fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0600);
- fd = open("/sys/log", O_WRONLY | O_APPEND | O_CREAT, 0600);
- fopen.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> // 파일을 새로 만들때의 권한
int open (const char *path, ing oflag, [mode_t mode];
성공 시 파일 디스크립터를, 실패 시 -1을 리턴한다
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
int fd;
if ((fd = open(argv[1], O_RDWR)) == -1)
perror(argv[1]);
printf("파일 %s 열기 성공\n", argv[1]);
close(fd);
exit(0);
}
creat()
- path가 나타내는 파일을 생성하고 쓰기 전용으로 열며, 생성된 파일의 사용권한은 mode로 정한다
- 기존 파일이 있을 경우에는 그 내용을 삭제하고 연다
- open(path, WRONLY | O_CREAT | O_TRUNC, mode);와 동일하다
- prototype
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int creat(const char *path, mode_t mode);
성공 시 파일 디스크립터를, 실패 시 -1을 리턴한다
close()
- fd가 나타내는 파일을 닫는다
- prototype
#include <unistd.h>
int close(int fd);
성공 시 파일 디스크립터를, 실패 시 -1을 리턴한다
'not기초 > 시스템프로그래밍' 카테고리의 다른 글
[시스템프로그래밍]임의 접근 파일 (0) | 2019.03.15 |
---|---|
[시스템프로그래밍]시스템 호출 read()/write()/dup()/dup2() (0) | 2019.03.15 |
[시스템프로그래밍]파일 시스템 (0) | 2019.03.15 |
[시스템프로그래밍]시스템 호출 #개요 (0) | 2019.03.15 |
[시스템프로그래밍]리눅스 시스템 개요 (0) | 2019.03.15 |