open()
ํจ์
ํ์ผ์ ์ฌ๋ ์์คํ
ํธ์ถ ํจ์์ด๋ค.
์ฌ์ฉ์๊ฐ ํ์ผ์ ์ ๊ทผ(read, write ๋ฑ)ํ ์ ์๋๋ก ์ปค๋์๊ฒ ์์ฒญํ๋ ์ญํ ์ ํ๋ค.
ํจ์ ์ํ
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode); // ํ์ผ ์์ฑ ์ ๊ถํ ํ์
๋ฐํ๊ฐ
- ์ฑ๊ณต: ํ์ผ ๋์คํฌ๋ฆฝํฐ (0 ์ด์์ ์ ์)
- ์คํจ: -1 (์๋ฌ ๋ฐ์)
์ด fd๋ฅผ ํตํด read()
, write()
, close()
๋ฑ์ ์ ๋ฌํด์ ์ฌ์ฉํ๋ค.
์ฃผ์ flags
์ต์
๋ค
์ต์ | ์ค๋ช |
---|---|
O_RDONLY |
์ฝ๊ธฐ ์ ์ฉ์ผ๋ก ์ด๊ธฐ |
O_WRONLY |
์ฐ๊ธฐ ์ ์ฉ์ผ๋ก ์ด๊ธฐ |
O_RDWR |
์ฝ๊ธฐ + ์ฐ๊ธฐ |
O_CREAT |
ํ์ผ์ด ์์ผ๋ฉด ์์ฑ |
O_TRUNC |
์ด ๋ ๊ธฐ์กด ํ์ผ ๋ด์ฉ ์ญ์ |
O_APPEND |
ํ์ผ ๋์๋ง ์ฐ๋๋ก ๊ฐ์ |
O_EXCL |
O_CREAT ์ ํจ๊ป ์ฌ์ฉ ์, ํ์ผ ์์ผ๋ฉด ์คํจ |
O_CREAT
๋ฅผ ์ฐ๋ฉด ์ธ ๋ฒ์งธ ์ธ์ mode_t mode
(ํ์ผ ๊ถํ)๋ ๋ฃ์ด์ค์ผ ํ๋ค.
์์
int fd;
fd = open("data.txt", O_RDONLY);
if (fd == -1)
perror("open failed");
int fd = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
// ์ฐ๊ธฐ ์ ์ฉ, ์์ผ๋ฉด ์์ฑ, ์์ผ๋ฉด ๋ด์ฉ ์ญ์ , ๊ถํ 644
fcntl.h
<fcntl.h>
๋ ํ์ผ ์ ์ด ์ต์
(file control options)์ ์ ์ํ ํค๋ ํ์ผ์ด๋ค.
์ฃผ๋ก open()
ํจ์๋ ํ์ผ ๋์คํฌ๋ฆฝํฐ ๊ด๋ จ ์์
์ ํ ๋ ํ์ํ๋ค.
์ฃผ์ ๊ธฐ๋ฅ
- ํ์ผ ์ด๊ธฐ(open) ์ต์ ์์
์์์ ๋ดค๋ O_RDONLY
, O_WRONLY
, ...
- fcntl() ํจ์ ๊ด๋ จ ์ต์
fcntl()
์ ์ด๋ ค์๋ ํ์ผ ๋์คํฌ๋ฆฝํฐ์ ์์ฑ์ ์ค์ ํ๊ฑฐ๋ ์กฐํํ ๋ ์ฌ์ฉ๋๋ค.- ์: non-blocking ๋ชจ๋ ์ค์ , FD_CLOEXEC ์ค์ ๋ฑ
int flags = fcntl(fd, F_GETFL); // fd์ ํ์ฌ ํ๋๊ทธ ์กฐํ
fcntl(fd, F_SETFL, flags | O_NONBLOCK); // non-blocking ๋ชจ๋ ์ค์
- ํ์ผ ์ ๊ธ(locking) ๊ด๋ จ ๊ตฌ์กฐ์ฒด ๋ฐ ๋งคํฌ๋ก
F_SETLK, F_GETLK, F_SETLKW // ํ์ผ ์ ๊ธ/ํด์ ๋ช
๋ น์ด
struct flock // ํ์ผ ์ ๊ธ ์ ๋ณด๋ฅผ ๋ด๋ ๊ตฌ์กฐ์ฒด
unistd.h
vs fcntl.h
<unistd.h>
:read()
,write()
,close()
,lseek()
๋ฑ ์์คํ ์ฝ ํจ์<fcntl.h>
:open()
์ฉ ์ต์ ,fcntl()
๊ธฐ๋ฅ ๋ฑ ์ ์ด ๊ด๋ จ ์์์ ์ ์
'๐โโ๏ธ Activities > 42 Cursus' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[get_next_line][C] read & write ํจ์ (0) | 2025.06.04 |
---|---|
[get_next_line][C] static ํจ์ & ๋ณ์ (0) | 2025.06.04 |
[get_next_line][C] ํ์ผ ๋์คํฌ๋ฆฝํฐ(File Descriptor) (0) | 2025.06.02 |
[ft_printf][C] printf ํฌ๋งท ์ถ๋ ฅ ์์ (%p, %u, %x, %X) (0) | 2025.06.02 |
[ft_printf][C] ๊ฐ๋ณ ์ธ์ ํจ์ (0) | 2025.06.02 |