C,C++ & Linux

C/C++ open 함수 - 파일 생성 / 읽기 / 쓰기

KyooDong 2020. 4. 21. 23:22
728x90

Open 함수 기능

파일을 열거나 생성 후 열어주는 함수

함수원형

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int open(const char *filepath, int flag);
int open(const char *filepath, int flag, mode_t mode);

매개변수

const char *filepath

열고자 하는 파일의 경로

 

int flag

파일 열 때 사용할 옵션

 

O_RDONLY : 읽기 모드 (Read Only)

O_WRONLY : 쓰기 모드 (Write Only) - 읽지 않고 쓰기만 하는 경우는 크게 많지 않음

O_RDWR : 읽기/쓰기 모드

O_CREAT : 파일 생성

O_APPEND : 파일을 쓰되 기존 파일의 맨 끝부터 이어 쓰는 기능

O_TRUNC : 파일을 초기화

O_EXCL : O_CREAT 와 함께 사용되며, 이미 파일이 존재한다면 에러를 리턴

 

mode_t mode

O_CREAT 옵션을 쓸 때 필수적으로 사용해야하는 옵션으로, 파일의 접근 권한을 명시

기본 값

파일 : 0666

디렉토리 : 0777

 

아래 옵션들은 bitwise 연산으로 여러개를 동시에 사용가능함

S_IRWXU : 유저 읽기, 쓰기, 실행 권한 (Read, Write, Execute User)

S_IRUSR : 유저 읽기 권한 (Read User)

S_IWUSR : 유저 쓰기 권한 (Write User)

S_IXUSR : 유저 실행 권한 (Execute User)

S_IRWXG : 그룹 읽기, 쓰기, 실행 권한 (Read, Write, Execute Group)

S_IRGRP : 그룹 읽기 권한

S_IWGRP : 그룹 쓰기 권한
S_IXGRP : 그룹 실행 권한

S_IRWXO : 기타 사용자 읽기, 쓰기, 실행 권한 (Read, Write, Execute Other)

S_IROTH : 기타 사용자 읽기 권한
S_IWOTH : 기타 사용자 쓰기 권한
S_IXOTH : 기타 사용자 실행 권한

 

반환 값

성공 시 0, 실패 시 -1 을 리턴하고 errno 설정

예제

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main() {
	char *fname = "ssu_test.txt";
	int fd;

	if ((fd = open(fname, O_RDONLY)) < 0) {
		fprintf(stderr, "open error for %s\n", fname);
		exit(1);
	}

	printf("Success!\nFilename : %s\nDescriptor : %d\n", fname, fd);
	exit(0);
}

결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

리눅스시스템프로그래밍 저자 : 홍지만
https://book.naver.com/bookdb/book_detail.nhn?bid=14623672

책에 기술된 예제 프로그램입니다. 책 내부에는 훨씬 더 많은 자료가 있습니다. (개인적으로 좋았습니다.)