open, read, close 함수는 주로 C 언어에서 파일을 다룰 때 사용된다.
함수들은 각각 파일을 열고, 파일에서 데이터를 읽고, 파일을 닫는 기능을 수행한다.
open() 함수는 파일을 열거나 생성하는 데 사용된다.
#include <fcntl.h>
int open(const char *pathname, int flags, mode_t mode);
| 플래그 | 설명 |
|---|---|
| O_RDONLY | 읽기 전용 모드 |
| O_WRONLY | 쓰기 전용 모드 |
| O_RDWR | 읽기/쓰기 모드 |
| O_CREAT | 파일이 없으면 생성 |
| O_APPEND | 파일 끝에 데이터 추가 |
| O_TRUNC | 파일을 열 때 내용 삭제 |
read() 함수는 열린 파일에서 데이터를 읽어온다.
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
close() 함수는 열린 파일을 닫는다.
#include <unistd.h>
int close(int fd);
#include <fcntl.h> #include <unistd.h> #include <stdio.h> #define BUF_SIZE 256 int main() { int fd; char buf[BUF_SIZE]; ssize_t bytes_read; // 파일 열기 fd = open("example.txt", O_RDONLY); if (fd == -1) { perror("파일 열기 실패"); return 1; } // 파일 읽기 bytes_read = read(fd, buf, BUF_SIZE - 1); if (bytes_read == -1) { perror("파일 읽기 실패"); close(fd); return 1; } // 널 문자 추가 buf[bytes_read] = '\0'; printf("읽은 내용: %s\n", buf); // 파일 닫기 if (close(fd) == -1) { perror("파일 닫기 실패"); return 1; } return 0; }
이 예제는 example.txt 파일을 열어 읽어 내용을 출력하고 파일을 닫는 예제 코드이다.
위 코드에 오류 처리하는 perror 함수가 있다.
perror은 C 언어에서 오류 메시지를 출력하는 데 사용되는 표준 라이브러리 함수다.
이 함수는 프로그램 실행 중 발생한 오류에 대한 설명을 표준 오류 스트림(stderr)에 출력한다.
void perror(const char *str);위 코드에서 작성된 오류처리를 보면 아래와 같다.
// 파일 열기
fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("파일 열기 실패");
return 1;
}
output
파일 열기 실패: No such file or directory