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\n");

 close(fd);
    return 0;
}

转载于:https://www.cnblogs.com/wsw-seu/p/8280403.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值