【Linux系统编程】10.open/close函数

目录

open

参数pathname

参数flags

主类

副类

参数mode

返回值

close

参数fp

测试代码

测试结果

错误处理函数

open

查看open函数

man 2 open

 其中

#include <unistd.h>

 包含

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

参数pathname

打开文件的路径、文件名。

参数flags

可选择两类参数进行传递,分别是主类和副类。主副两类参数可搭配使用。

主类

只允许使用一个,不可同时使用。

  • O_RDONLY: 以只读方式打开。

  • O_WRONLY: 以只写方式打开。

  • O_RDWR: 以可读可写方式打开。

副类

可多个搭配使用。

  • O_CREAT: 如果文件不存在则创建该文件。

  • O_EXCL: 如果使用O_CREAT选项且文件存在,则返回错误消息。

  • O_NOCTTY: 如果文件为终端,那么终端不可以调用open系统调用的那个进程的控制终端。

  • O_TRUNC: 如果文件已经存在则删除文件中原有数据。

  • O_APPEND: 以追加的方式打开。

参数mode

如果文件被新建,指定其权限为mode。 mode为八进制权限码。

返回值

成功:打开文件所得到对应的文件描述符,整型的数据。

失败:-1,设置eerno。

close

查看close函数

man 2 close

参数fp

打开文件所得到对应的文件描述符。

测试代码

#include <unistd.h>
#include <fcntl.h>		//为flags参数服务
#include <stdio.h>

int main(){
    int fp,close_num;
    fp=open("./aaa.txt",O_RDWR|O_CREAT,0644);	//以读写的方式打开,如果该文件不存在则创建,创建的权限为644
    printf("fp=%d\n",fp);
    close_num=close(fp);
    printf("cloase_num:%d\n",close_num);
    return 0;
}

测试结果

错误处理函数

#incldue <errno.h>
printf("error:%s\n",strerror(errno));
perror("xxx error")

猜你喜欢

转载自blog.csdn.net/CETET/article/details/130063390