Linux (C/C++) operation open, fopen and freopen

Insert picture description here

File operations open, fopen and freopen under Linux (C/C++)

open is the underlying system call function under linux, fopen and freopen standard I/O library functions under c/c++, with input/output buffer. The fopen under linxu is an encapsulation function of open, and fopen will eventually call the underlying system call open.
Therefore, if you need to explicitly control the device under Linux, it is best to use the underlying system call (open),

File operations corresponding to open include: close, read, write, ioctl, etc.
File operations corresponding to fopen include: fclose, fread, fwrite, freopen, fseek, ftell, rewind, etc.
freopen is a function used to redirect input and output streams. This function can change the input and output environment without changing the original appearance of the code, but the stream should be reliable when used.

The difference between open and fopen:

  • Fread is buffered, and read is not buffered.
  • fopen is defined in standard c, and open is defined in POSIX.
  • fread can read a structure.read reads binary in linux/unix and it is no different from ordinary files.
  • fopen cannot specify the permissions of the file to be created. open can specify the permissions
  • fopen returns the file pointer, and open returns the file descriptor (integer).
  • Any device in linux/unix is ​​a file, you can use open and read.

1. Open system call (linux)

Need to include the header file:
#include<sys/types.h>
#include<sys/
stat.h> #include<fcntl.h>

Function prototype:
int open( const char * pathname, int oflags);
int open( const char * pathname,int oflags, mode_t mode);

mode is used only when creating a new file, and is used to specify file access permissions.
pathname is the path name of the file to be opened/created;
oflags is used to specify the opening/creation mode of the file. This parameter can be composed of the following constants (defined in fcntl.h) through logical OR.
O_RDONLY Read only mode
O_WRONLY Write only mode
O_RDWR Read and write mode The
above three are mutually exclusive, that is, they cannot be used at the same time.
When opening/creating a file, at least one of the above three constants must be used. The following constants are optional:
O_APPEND Each write operation writes to the end of the file
O_CREAT If the specified file does not exist, the file is created
O_EXCL If the file to be created already exists, it returns -1, and the value of errno is modified
O_TRUNC If the file Exist and open in write-only/read-write mode, the entire contents of the file will be cleared.
O_NOCTTY If the path name points to a terminal device, do not use this device as a control terminal.
O_NONBLOCK If the path name points to a FIFO/block file/character file, set the file opening and subsequent I/O to nonblocking mode (nonblocking mode).
//The following is used to synchronize input and output
O_DSYNC and wait for the physical I/O to end before writing. Without affecting the reading of newly written data, it does not wait for file attribute updates.
O_RSYNC read Wait for all write operations to the same area to complete before performing
O_SYNC Wait for the physical I/O to end before writing , including I/O to update file attributes

When you use the open call with the O_CREAT flag to create a file, you must use the open call with 3 parameter formats. The third parameter mode is obtained by bitwise OR of several flags.
These flags are defined in the header file sys/
stat.h , as shown below: S_IRUSR: read permission, file owner
S_IWUSR: write permission, file owner
S_IXUSR : Execution permission, file owner
S_IRGRP: read permission, file belongs to group
S_IWGRP: write permission, file belongs to group
S_IXGRP: execute permission, file belongs to group
S_IROTH: read permission, other users
S_IWOTH: write permission, other users
S_IXOTH: execute permission, Other users

Return value : Return the file descriptor if successful, otherwise -1. Return the file descriptor (integer variable 0~255). The file descriptor returned by open must be the smallest descriptor not yet used by the process. As long as one permission is forbidden, -1 is returned.

Error code : (All have the beginning of E, remove it is the word or word abbreviation about the error)
The file pointed to by the EEXIST parameter pathname already exists, but the O_CREAT and O_EXCL flags are used.
The file pointed to by the EACCESS parameter pathname does not meet the required test permissions.
EROFS The file to be tested for write permission exists in the read-only file system.
The EFAULT parameter pathname pointer exceeds the accessible memory space.
The EINVAL parameter mode is incorrect.
ENAMETOOLONG parameter pathname is too long.
ENOTDIR parameter pathname is not a directory.
ENOMEM insufficient core memory.
ELOOP parameter pathname has too many symbolic links.
EIO I/O access error.
ssize_t write(int fd, const void *buf, size_t count);
Parameters :
fd: the file description word to be written.
buf: buffer to be output
count: maximum output byte count
Return value : return the number of bytes written successfully, return -1 on error and set errno
ssize_t read(int fd, void *buf, size_t count);
Parameters :
buf : The buffer to be read
count: the maximum read byte count
Return value: Return the number of bytes read successfully, return -1 on error and set errno, if the end of the file is reached before the read is adjusted, the read returns 0 this time.

(More free C/C++, Linux, Nginx, ZeroMQ, MySQL, Redis, fastdfs, MongoDB, ZK, streaming media, CDN, P2P, K8S, Docker, TCP/IP, coroutine, DPDK, etc. advanced knowledge points Advanced dry goods learning materials plus group 960994558)
Insert picture description here

2. fopen library function

Header file : <stdio.h>
Function prototype : FILE * fopen(const char * path, const char * mode); The
path string contains the file path and file name to be opened, and the parameter mode string represents the stream form.
Mode has the following types of strings:
"r" or "rb" To open a file in read-only mode, the file must exist.
"W" or "wb" opens the file in writing mode and shortens the file length to zero.
"A" or "ab" opens the file in writing mode, and the new content is appended to the end of the file.
"r+" or "rb+" or "r+b" open in update mode (read and write)
"w+" or "wb+" or "w+b" open in update mode, and shorten the file length to zero.
"a+" or "ab+" or "a+b" is opened in update mode, and the new content is appended to the end of the file.
The letter b means that the file is a binary file rather than a text file. (There is no distinction between binary files and text files under Linux)
Return value : After the file is successfully opened, the file pointer to the stream will be returned. If the file fails to open, NULL is returned and the error code is stored in errno.

fread is a function. Read data from a file stream, read up to count elements, each element size bytes, if the call is successful, return the number of elements actually read, if it is unsuccessful or read to the end of the file, return 0.
Function prototype : size_t fread (void *buffer, size_t size, size_t count, FILE *stream);
Parameters :
buffer: the memory address used to receive data
size: the number of bytes to be read and written, the unit is byte
count: to be performed How many size bytes of data items are read and written, each element is size bytes.
stream: input stream
return value : the number of elements actually read. If the return value is not the same as count, the end of the file or an error may occur. Get error information from ferror and feof or check whether the end of the file is reached.

fwrite: write a data block to the file.
Function prototype : size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);
Parameters :
buffer: is a pointer, for fwrite, it is the address to get the data ;
Size: the number of single bytes
to be written ; count: the number of data items to be written to size bytes;
stream: the target file pointer;
return value : return the number of data blocks actually written

fflush: Write out all the data in the file stream immediately.
Function prototype : int fflush(FILE *stream);

fseek: is the file stream function corresponding to the lseek system call. It specifies a position in the file stream for the next read and write operation.
Function prototype: int fseek(FILE *stream, long offset, int fromwhere); The
parameter stream is the file pointer. The
parameter offset is the offset. A positive number indicates a positive offset, and a negative number indicates a negative offset. The
parameter fromwhere is set from the file Where to start the offset, the possible values ​​are: SEEK_CUR, SEEK_END or SEEK_SET
SEEK_SET: the beginning of the file SEEK_CUR: the
current position
SEEK_END: ​​the end of the file
where SEEK_SET, SEEK_CUR and SEEK_END are 0, 1, and 2.
Return value : If the execution is successful, stream will Point to the position offset by offset (pointer offset) bytes based on fromwhere, the function returns 0. If the execution fails (for example, the offset exceeds the size of the file itself), the position pointed to by the stream is not changed, and the function returns a non-zero value.

The following is a program to open a file and display the contents of the file under Linux:
Insert picture description here
Insert picture description here

3、freopen

Function prototype : FILE * freopen (const char * filename, const char * mode, FILE * stream );
Parameters :
filename: the name of the file to be opened
mode: the mode of file opening, which is the same as the mode in fopen (r/w)
stream : File pointer, usually standard stream file (stdin/stdout/stderr).
Return value : If successful, return the pointer to the stream, otherwise NULL.
Role: A function used to redirect input and output streams, redirecting standard input, output, error or file stream in stream to the content in the filename file. It is easy to use the redirection output under linux. /program name>test (>>test append), the input and output redirection under windows can use freopen.
61. How to use: Because the file pointer uses a standard stream file, we don't need to define the file pointer.
62. We use the freopen() function to open the input file test.in in read-only mode r(read), freopen("test.in", "r", stdin);
63. In this way, the input of the program will be from the standard input stream Convert stdin to input
64 from the file "test.in". Then use the freopen() function to open the output file test.out in writing mode w(write), freopen("test.out", "w", stdout);
The output of the program will change from the original standard output to the file "test.out"

There may be shortcomings in the above, welcome to point out the discussion, friends who feel good hope to get your forwarding support, and can continue to follow me.

Guess you like

Origin blog.csdn.net/weixin_52622200/article/details/110290187