One, the file descriptor
For Linux, all operations on a device or file are performed through a file descriptor. When a file is opened or created, the kernel returns a file descriptor (non-negative integer) to the process. Subsequent operations on the file simply pass the file descriptor, and the kernel records information about the open file (the file structure).
When a process starts, 3 files are opened by default, standard input, standard output, standard error, corresponding file descriptor is 0 (Stdin_fileno), 1 (Stdout_fileno), 2 (Stderr_fileno), these constants are defined in the Unistd.h header file.
In addition, the following two functions are described:
Fileno: Converting a file pointer to a file descriptor
Fdopen: Converting a file descriptor to a file pointer
Second, what is I/O
Input/output is the process of copying data between main memory and external devices
Device--memory (input operation)
memory, device (output operation)
Advanced I/O
Standard I/O libraries provided by ANSI C are referred to as advanced I/O, often referred to as buffered I/O
Low-level I/O
Commonly referred to as non-buffered I/O
Iii. opening and closing of files
Open System call 1:
Function prototypes
int open (const char *path, int flags);
Parameters
Path: The name of the file that can contain (both absolute and relative) paths
Flags: File open mode
return value:
Open successfully, return file descriptor; Open failed, return-1
Open System Call 2:
Function prototypes
int open (const char *path, int flags,mode_t mode);
Parameters
Path: The name of the file that can contain (both absolute and relative) paths
Flags: File open mode
Mode: Used to specify the owner of the file, the user group of the file, and the access rights of other users in the system
return value:
Open successfully, return file descriptor; Open failed, return-1
Here is the mode in which the file opens:
O_rdonly Open a file for reading
O_wronly Open a file for writing
O_rdwr Open a file to read and write
All data written by O_append will be appended to the end of the file
O_creat Open File, if file does not exist then build file
O_EXCL Force open () fails if o_creat is already placed and the file exists
O_trunc Empty the contents of the file when open ()
O_cloexec closes the open file descriptor when the exec process substitution is made.
Specifying this flag permits a program to avoid additional fcntl (2) F_SETFD operations to set the FD_CLOEXEC flag.
O_nonblock non-blocking mode
Linux system Programming-File Open close