- Input/output is the process of copying data between the primary and external devices.
Device> memory (input operation)
Memory-> device (output Operation)
The standard I/O library provided by ansi c is called Advanced I/O, also known as I/O with buffer
It is also known as I/O without buffering.
2. file descriptor: fd
- For Linux, all operations on devices or files are performed through file descriptors.
- When a file is opened or created, the kernel returns a file descriptor (non-negative integer) to the process ). Subsequent operations on the file only need to use the file descriptor to record information about the opened file.
- When a process starts, three files are opened by default, including standard input, standard output, and standard error. The corresponding file descriptors are 0 (STDIN_FILENO), 1 (STDOUT_FILENO), and 2 (STDERR_FILENO ), these constants are defined in unistd. h header file. The C library functions correspond to stdin, stdout, and stderr, but these three are FILE pointer types.
3. file descriptor and file pointer Conversion
You can use the following two functions:
- Fileno: converts a file pointer to a file descriptor.
# Include <stdio. h>
Int fileno (FILE * stream)
Test procedure:
#include <stdlib.h><stdio.h>
main(
Test result: <sys/types. h> <sys/stat. h> <fcntl. h> <stdlib. h> <stdio. h> <errno. h> <. h> ERR_EXIT (m) \ (main (= open (, O_WRONLY | O_CREAT, (fd =-
Test result 1: The default umask value is used.
Test result 2: reset the umask value.
To reuse the file descriptor, call the close () system to release the opened file descriptor.
Function prototype:
# Include <unistd. h>
Int close (int fd );
Function parameters:
-Fd: file descriptor of the file to be closed
Return Value
If an error occurs,-1 is returned.
0 is returned if the call is successful.
NOTE: If close () is not displayed, the file is closed when the program exits.
To maintain backward compatibility with earlier UNIX systems, Linux also provides optional system calls for file creation, called creat (). In modern linux kernels, creat is rarely used to create files, because open can complete the creation function.
Function prototype:
Int creat (const char * path, mode_t mode );
Parameters
Path: file name, which can contain (absolute and relative) paths
Mode: Specifies the access permissions of the owner of the file, the user group of the file, and other users in the system.
Return Value
Open successfully. The file descriptor is returned;
Opening failed.-1 is returned.
In earlier versions of UNIX, open () system calls only have two parameters. If the file does not exist, it cannot open the file. The creation of the file is completed by a separate system call creat. In Linux and all modern UNIX versions, creat () system calls are redundant.
Creat () call
Fd = creat (file, mode );
It is equivalent to the modern open () call.
Fd = open (file, O_WRONLY | O_CREAT | O_TRUNC, mode );