open函数

1.查看linux系统I/O函数格式:man 2 函数名

nowcoder@nowcoder:~/linux$ man 2 open

2.查看标准C库I/O函数格式: man 3 函数名

nowcoder@nowcoder:~/linux/lession09$ man 3 perror
  1. 在这里插入图片描述
  // 打开一个已经存在的文件
    int open(const char *pathname, int flags);
        参数:
            - pathname:要打开的文件路径
            - flags:对文件的操作权限设置还有其他的设置
              O_RDONLY,  O_WRONLY,  O_RDWR  这三个设置是互斥的
        返回值:返回一个新的文件描述符,如果调用失败,返回-1
           	- open 

    errno:属于Linux系统函数库,库里面的一个全局变量,记录的是最近的错误号。

    #include <stdio.h>
    void perror(const char *s);作用:打印errno对应的错误描述
        s参数:用户描述,比如hello,最终输出的内容是  hello:xxx(实 际的错误描述)
    

    // 创建一个新的文件
    int open(const char *pathname, int flags, mode_t mode);
    参数:
            - pathname:要创建的文件的路径
            - flags:对文件的操作权限和其他的设置
                - 必选项:O_RDONLY,  O_WRONLY, O_RDWR  这三个之间是互斥的
                - 可选项:O_CREAT 文件不存在,创建新文件
            - mode:八进制的数,表示创建出的新的文件的操作权限,比如:0775
            最终的权限是:mode & ~umask
            0777   ->   111111111
        &   0775   ->   111111101
        ----------------------------
                        111111101
        按位与:0和任何数都为0
        umask的作用就是抹去某些权限。

        flags参数是一个int类型的数据,占4个字节,32位。
        flags 32个位,每一位就是一个标志位。
           	

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

int main(){

    int fd = open("a.txt",O_RDONLY);
    
    if(fd == -1){
        perror("open");
    }
    //关闭
    close(fd);
    return 0;

}
nowcoder@nowcoder:~/linux$ cd lession09
nowcoder@nowcoder:~/linux/lession09$ ls
open.c
nowcoder@nowcoder:~/linux/lession09$ gcc open.c -o open
nowcoder@nowcoder:~/linux/lession09$ ls
open  open.c
nowcoder@nowcoder:~/linux/lession09$ ./open
open: No such file or directory

文件中没有a.txt,报出错误信息open: No such file or directory

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {

    // 创建一个新的文件
    int fd = open("create.txt",O_RDWR| O_CREAT, 0777);

    if(fd == -1){
        perror("open");
    }
    close(fd);
    return 0;
}
nowcoder@nowcoder:~/linux/lession09$ gcc create.c -o create
nowcoder@nowcoder:~/linux/lession09$ ls
create  create.c  create.txt  open  open.c
nowcoder@nowcoder:~/linux/lession09$ ll create.txt
-rwxrwxr-x 1 nowcoder nowcoder 0 3-р с  4 16:24 create.txt*

本来没有create.txt文件,自动创建了一个,注意open的第二个参数如果有多个用 | 连接,这是因为第二个参数是32位的int类型,每一位bit代表一位可执行操作,所以用或字符才能实现所有想要的操作

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值