[Linux system programming] 10. open/close function

Table of contents

open

parameter pathname

parameter flags

main class

Subclass

parameter mode

return value

close

parameter fp

test code

Test Results

error handling function

open

View the open function

man 2 open

 in

#include <unistd.h>

 Include

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

parameter pathname

The path and file name of the open file.

parameter flags

Two types of parameters can be selected for transmission, namely the main class and the subclass. The primary and secondary parameters can be used together.

main class

Only one is allowed, not both.

  • O_RDONLY : Open as read-only.

  • O_WRONLY : Open for writing only.

  • O_RDWR : Open in readable and writable mode.

Subclass

Can be used in multiple combinations.

  • O_CREAT : Create the file if it does not exist.

  • O_EXCL : Returns an error message if the O_CREAT option is used and the file exists.

  • O_NOCTTY : If the file is a terminal, then the terminal cannot call the controlling terminal of the process of the open system call.

  • O_TRUNC : If the file already exists, delete the original data in the file.

  • O_APPEND : Open in append mode.

parameter mode

If the file is created, specify its permissions as mode. mode is an octal permission code.

return value

Success : Open the file to get the corresponding file descriptor and integer data.

Failed : -1, set eerno.

close

View the close function

man 2 close

parameter fp

The corresponding file descriptor obtained by opening the file.

test code

#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;
}

Test Results

error handling function

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

Guess you like

Origin blog.csdn.net/CETET/article/details/130063390