server-api-open

原型

文件描述符、套接字等打开函数。
打开文件返回的文件描述符的值为3,因为0(标准输入)、1(标准输出)、2、(标准错误)文件描述符在程序启动的时候默认分配的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// path:文件的名称,可以包含(绝对和相对)路径
// flags:文件打开模式(#include<fcntl.h>)
// O_RDONLY:打开一个供读取的文件
// O_WRONLY:打开一个供写入的文件
// O_RDWR:打开一个可供读写的文件
// O_APPEND:写入的所有数据将追加到文件的末尾
// O_CREAT:打开文件,如果文件不存在则创建文件
// O_EXCL:如果已经置O_CREAT且文件存在,则open()失败
// O_TRUNC:在open()时,将文件的内容清空
// mode:访问权限(可以用数字代替0666...)
// S_IRWXU(00700):用户(文件所有者)有读写和执行的权限
// S_IRUSR(00400):用户对文件有读权限
// S_IWUSR(00200):用户对文件有写权限
// S_IXUSR(00100):用户对文件有执行权限
// S_IRWXG(00070):组用户(文件所有者)有读写和执行权限
// S_IRGRP(00040):组用户读文件有读权限
// S_IWGRP(00020):组用户对文件有写权限
// S_IXGRP(00010):组用户对文件有执行权限
// S_IRWXO(00007):其他用户(文件所有者)有读写有执行的权限
// S_IROTH(00004):其他用户对文件有读权限
// S_IWOTH(00002):其他用户对文件有写权限
// S_IXOTH(00001):其他用户对文件有执行权限
// 返回值:
// 打开成功,返回文件描述符;
// 打开失败,返回-1
int open(const char* path, int flags)
int open(const char* path, int flags, mode_t mode);

使用参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

/*
#define ERR_EXIT(m) (perror(m), exit(EXIT_FAILURE))
*/

#define ERR_EXIT(m)\
do \
{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)

int main()
{
umask(0); // 自定义umask而不使用系统默认的
int fd;
fd = open("test.txt", O_WRONLY | O_CREAT, 0666); // 0666 & ~系统的umask = 0644
/* if(fd == -1)
{
fprintf(stderr, "open error with errno=%d %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
*/

if(fd == -1)
ERR_EXIT("open error");

printf("open success\n");
close(fd);
return 0;
}