
34
|
第二章
int fd;
fd = open (file, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd ==
−
1)
/* 錯誤 */
creat() 函式
由於
O_WRONLY | O_CREAT | O_TRUNC
的組合太常見了,所以存在一個系統呼叫專門提供此
行為:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int creat (const char *name, mode_t mode);
沒錯,函式的名字漏掉了一個「e」。 Unix 的創造者 Ken Thompson 曾經
開玩笑地說,設計 Unix 的當時漏掉字母是他最大的遺憾。
下面是典型的
creat()
呼叫用法:
int fd;
fd = creat (filename, 0644);
if (fd ==
−
1)
/* 錯誤 */
其行為如同下面的程式碼:
int fd;
fd = open (filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd ==
−
1)
/* 錯誤 */
多數 Linux 架構上,
3
creat()
是一個系統呼叫,儘管在用戶空間中實作它很容易:
int creat (const char *name, int mode)
{
return open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
}
3