int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
O_RDONLY只读打开 O_WRONLY只写打开 O_RDWR可读可写打开
当我们附带了权限后,打开的文件就只能按照这种权限来操作。
以上三个常数中只能选择一个。下列常数是可选择的。
O_CREAT若文件不存在则创建它。使用此选项时,需要说明第三个参数mode,用其说明该文件的存取许可权限。
O_EXCL如果同时指定了O_CREAT,而文件已经存在,则出错。
O_APPEND每次写时都加到文件的尾端
O_TRUNC属性去打开文件时,如果这个文件本来是有内容的,而且只读或只写成功打开,则其长短截断为0.
mode:一定是flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限
文件file1原始内容:
O_EXCL代码示例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
fd = open("./file1",O_RDWR|O_CREAT|O_EXCL,0600);
if(fd = -1){
printf("file1 already exists\n");
}
close(fd);
return 0;
}
O_APPEND代码示例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fd;
int n_write;
char readBuf[128] = {'\0'};
char *buf = "Practice and review";
fd = open("./file1",O_RDWR|O_CREAT|O_APPEND,0600);
if(fd > 0){
printf("open file1 success fd = %d\n",fd);
}
n_write = write(fd,buf,strlen(buf));
printf("write %d byte\n",n_write);
close(fd);
return 0;
}
O_TRUNC代码示例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fd;
int n_write;
char readBuf[128] = {'\0'};
char *buf = "Practice and review";
fd = open("./file1",O_RDWR|O_CREAT|O_TRUNC,0600);
if(fd > 0){
printf("open file1 success fd = %d\n",fd);
}
n_write = write(fd,buf,strlen(buf));
printf("write %d byte\n",n_write);
close(fd);
return 0;
}