天天看点

linux 系统调用 open函数使用

函数介绍

本文仅仅将​

​open​

​系统调用的使用简单总结一下,关于其实现原理大批的大佬分享可以自行学习。open系统调用主要用于打开或者创建一个文件,并返回文件描述符。

  • 头文件 ​

    ​#include <fcntl.h>​

  • 函数名称

    a. ​​

    ​int open(const char *pathname, int flags);​

    ​​

    b. ​​

    ​int open(const char *pathname, int flags, mode_t mode);​

以上两个函数参数含义如下:

  • pathname 字符串类型的文件名称,“a.txt”
  • flags 为 以什么样的方式打开文件,主要包括三种​

    ​O_RDONLY​

    ​​, ​

    ​O_WRONLY​

    ​​, or ​

    ​O_RDWR​

    ​​,分别是只读方式,只写方式以及读写方式。

    此外还有更多的打开方式的标记,可以通过​​

    ​man open​

    ​命令详细查看
  • mode 为打开文件时赋予的文件用户,用户组权限

    可以通过设置​​

    ​0777​

    ​​八进制这种方式来设置,也可以通过​

    ​S_IRWXU​

    ​​类型 的标准mode来设置。标准用户权限模式如下几种,该权限的设置可以通过​

    ​|​

    ​​符号来叠加

    a. ​​

    ​S_IRWXU​

    ​​ 00700文件拥有者读,写,可执行权限

    b. ​​

    ​S_IRUSR​

    ​​ 00400 文件拥有者读权限

    c. ​​

    ​S_IWUSR​

    ​​ 00200 文件拥有者写权限

    d. ​​

    ​S_IXUSR​

    ​​ 00100 文件拥有者可执行权限

    e. ​​

    ​S_IRWXG​

    ​​ 00070 文件用户组读,写,可执行权限

    f. ​​

    ​S_IRGRP​

    ​​ 00040 文件用户组读权限

    g. ​​

    ​S_IWGRP​

    ​​ 00020 文件用户组写权限

    h. ​​

    ​S_IXGRP​

    ​​ 00010 文件用户组可执行权限

    i. ​​

    ​S_IRWXO​

    ​​ 00007 其他用户读,写,执行权限

    j. ​​

    ​S_IROTH​

    ​​ 00004 其他用户读权限

    k. ​​

    ​S_IWOTH​

    ​​ 00002 其他用户写权限

    l. ​​

    ​S_IXOTH​

    ​ 00001 其他用户可执行权限

函数使用

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
        int fd;
        if (argc < 2) {
                printf("./a.out filename \n");
                exit(1);
        }

        umask(0);
        //这里关于文件不存在,则创建时赋予文件的权限两种方式是一样的,这里赋予的是00770权限
        //fd=open(argv[1],O_CREAT | O_RDWR, S_IRWXU|S_IRWXG);
        fd=open(argv[1],O_CREAT | O_RDWR, 0770);

        printf("%d\n",fd);
        close(fd);
        return 0;
}      
zhang@ubuntu:~/test$ gcc test_open.c 
zhang@ubuntu:~/test$ ./a.out test.txt
3
zhang@ubuntu:~/test$ ls -l test.txt 
-rwxrwx--- 1 zhang zhang 0 Sep 15 03:37 test.txt