1、Linux下open的使用

函数:open

在终端输入命令

man 2 open

跳转以下页面

要使用这个API就要包含这些头文件 ,在终端都会有显示。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

函数参数的说明:

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

int creat(const char *pathname, mode_t mode);


//pathname:要打开的文件名(含路径,缺省为文件名);

//flags:
O_RDONLY 只读打开      O_WRONLY 只写打开   O_RDWR可读可写打开

Mode:一定是在flags中使用了O_CREAT标志,mode记录创建文件访问权限。

我们先编程体验下这个函数,在当前路径下创建一个文件,暂且叫file1;之后写代码如下:

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

int main()
{
    int fd;
    fd = open("./file1",O_RDWR);//file1是我们新创建的文件

    printf("fd = %d \n",fd);

    return 0;
}

打开成功返回的值是3,如果我们删掉file1这个文件,那么返回值是-1;或者把file1改成一个不存在的文件,返回值也是-1;

我们在体验下带3个参数的open函数,第3个参数是权限;

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

int main()
{
    int fd;
    fd = open("./file1",O_RDWR);

    if(fd == -1)
    {
        printf("open file1 failed\n");
        fd = open("./file1",O_RDWR|O_CREAT,0600);//0600的权限是可读可写
        if(fd > 0 )
        {
            printf("creat file1 success !\n");

        }
    }
    printf("fd = %d \n",fd);

                                                              1,1          顶端
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值