ファイルが存在しなければ新規作成
# include <unistd.h>
# include <sys/types.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <stdio.h>
# include <stdlib.h>
int fd;
int flags;
mode_t mode;
errno = 0;
flags = O_WRONLY | O_CREATE | O_TRUNC // 書き込み用に新規作成
| O_CLOEXEC // クローズ・オン・エクゼックする
| O_EXCL; // シンボリックリンクか既に存在する場合こけさせる
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // 0644
if( (fd = open("hoge", flags, mode)) == -1) {
perror("open");
exit(1); // リソースの破棄はシステムまかせ
}
ファイルが既に存在していても操作したい。
int file_remove()
{
int fd;
errno = 0;
if( (fd = open("hoge", O_RDONLY | O_CLOEXE)) == -1 ) {
return 0; // 消してない
}
// 名前を消す,他のプロセスがファイルを開いていなければファイルも消える.
if( (unlink("hoge")) == -1) {
perror("unlink")
exit(1);
}
return 1; // けしたよ!
}
int file_create()
{
int fd;
int flags;
errno = 0;
flags = O_WRONLY | O_CREATE | O_TRUNC | O_CLOEXEC;
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
file_remove() // 根っ子になる条件で再帰させる
if( (fd = open("hoge", flags, mode)) == -1 ) {
perror("open");
exit(1);
}
return fd;
}
通常ファイルか判定
int fd;
int regfile;
struct stat info;
errno = 0;
if( (fd = open("hoge", O_RDONLY | O_CLOEXE)) == -1 ) {
exit(1);
}
if( (stat("hoge", &info)) == -1 ) {
perror("stat");
exit(2);
}
return regfile = S_ISREG(info.st_mode) ? 1 : 0;
クローズ・オン・エグゼック フラグをあとから追加
int flags;
int fd;
fd = open(...);
flags = fcntl(fd, F_GETTD);
flags |= FD_CLOEXEC;
fcntl(fd, F_SETFD, flags);