Library function:
#include <fcntl.h>
Function prototype
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
pathname : The path name of the file to be opened or created, which can be an absolute path or a relative path.
flags : When opening a file, you can pass in multiple parameter options, and use one or more of the following to perform an "or" operation to form flags;
O_RDONLY : read-only open;
O_WRONLY : write-only open;
O_RDWR : open for reading and writing; (only one of the above three variables can be specified)
O_CREAT : If the file does not exist, create it. Need to use the mode (file permission flag) option to indicate the access permission of the new file;
O_APPEND : additional write, each write will be appended to the end of the file;
O_TRUNC : Delete all the contents of the original file and then open the file;
O_EXCL : If the file to be created already exists, an error will occur when using O_CREAT and -1 will be returned. If the file does not exist, it will be created and the return value will be greater than 0;
mode : r : read permission ( 0400 ); w : write permission ( 0200 ); x : executable permission ( 0100 ); read and write ( 0600 ); read, write and execute ( 0700 );
Return value : If successful, it returns the descriptor of the open file. The file descriptor is a non-negative integer (usually 3). If it fails, it returns -1.
The file identifiers 0, 1, and 2 represent standard input, standard output, and standard error output, respectively, and are replaced by the constants STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO, respectively.
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd = open("./file1",O_RDWR);
if(fd == -1){
printf(" 打开 file1 文件失败 \n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf(" 创建 file1 文件成功 \n");
}
}
return 0;
}