creatは、openと同じでファイルを開くわけだが、openの第2引数に、O_CREAT|O_WRONLY|O_TRUNCのオプションを付けた状態と同じなので、既に存在しているファイルはサイズを0に切り詰めて、上書き保存のような形になる。
Man page of OPEN
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void){
int fd1;
fd1 = open("test.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd1 == -1){
perror("open(1)");
return -1;
}
write(fd1, "ABCDE", 5);
close(fd1);
return 0;
}
新規作成として、同じオプションをopenに指定。
$ vi creat.c
$ gcc creat.c -o creat
$ ./creat
$ ls
creat creat.c test.txt
$ cat test.txt
ABCDE$
新規作成され文字列が書き込まれる。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void){
int fd1;
int fd2;
char buf[32];
fd1 = open("test.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd1 == -1){
perror("open(1)");
return -1;
}
write(fd1, "ABCDE", 5);
close(fd1);
fd2 = open("test.txt", O_RDONLY);
if (fd2 == -1){
perror("open(2)");
return -2;
}
read(fd2, buf, 32);
printf("buf = %s\n", buf);
close(fd2);
return 0;
}
今度は読み込んでみる。
$ vi creat.c
$ gcc creat.c -o creat
$ ./creat
buf = ABCDE
$ ls
creat creat.c test.txt
$ cat test.txt
ABCDE$
こうなる。
creatで開いて、"XYZ"を書き込む。
$ vi creat.c
$ gcc creat.c -o creat
$ ./creat
buf = ABCDE
$ ls
creat creat.c test.txt
$ cat test.txt
XYZ$
"XYZ"に上書き保存されてる。
Sample/unixsyscall/creat/creat/src/creat at master · bg1bgst333/Sample · GitHub