open系统调用

/*

int open(const char *pathname, int flags, mode_t mode);
flag:打开方式,可以man 2 open查看

O_RDONLY    O_WRONLY    O_RDWR    O_APPEND    O_CREAT     O_EXCL    O_TRUNC)(open时将文件内容清空)

文件打开失败:

EACCES:没有权限,如果一个文件没有写的权限,我们以写的方式打开,就会出错。

EEXIST:文件已经存在,还用O_CREAT|O_EXCL这个方式打开

EFAULT:无效文件指针

EMFILE:超过一个进程能够打开的文件描述符的个数; 用ulimit -a/-n 查看   1024

ENFILE:超过系统能够支持的文件个数    cat  /proc/sys/fs/file-max  (与内存大小有关)

*/

例子:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.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值,不再从shell 中继承。这样就可以创建0666权限的文件
     int fd;//O_APPEND 将指针定位到末尾  O_TRUNC  清空
     //读方式打开一个文件

 //666-002逻辑减umask是默认丢弃的权限 newmode=mode&~umask0655---rw-r-xr-x -umask(002)----------w-=0655
    fd=open("test.txt",O_RDONLY|O_CREAT,0666);

 //fd=open("test2.txt",O_RDONLY|O_CREAT,S_IRUSR|S_IWUSR);  //或者用宏的方式来指定文件权限。0600
    if(fd==-1)
        ERR_EXIT("open error");
    printf("open succ ");

 close(fd);
    return 0;
}

原文地址:https://www.cnblogs.com/wsw-seu/p/8280403.html