File operation part of Linux programming

Preface

        Operations on files must follow the order of opening the file, operating the file, and closing the file. Closing the file is the most important. Because the file itself is a static file, a dynamic file will be created after opening the file, and the content of the static file will be loaded into the buf buffer of the dynamic file. All operations on the file are performed on buf. If the file is not closed, the static file will not be updated synchronously. After the file is closed, the static file will be updated synchronously.

Table of contents

        This article describes some functions commonly used to operate files under Linux: open() function, close() function, write() function,

read() function, lseek() cursor positioning function, and some minor problems.

open()

close()

write()

read()   

creat()

open()

Header file :  

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

Function prototype :

       int open(const char *pathname, int flags);
       int open(const char *pathname, int flags, mode_t mode);

  Function: Opening a file will return a file descriptor - an integer (file description is referred to as fd). The file descriptor runs through all file operation functions. Other functions can access the specified file based on fd.

Parameter description :

               1.pathname

                        The name of the file to be opened (including the path)

                2.flags

                        When opening a file, you can pass in one or two parameter options for the file access permissions.

                        O_RDONLY open read only

                        O_WRONLY Open for writing only

                        O_RDWR open for reading and writing

                  These three parameters are sometimes used and only one can be used (it is easy to understand, when you can't read or write, you can make it write-only)

                        O_CREAT Create the file if it does not exist. When using this option, you need to also specify the third parameter mode, which describes the access permissions of the new file.    If the file does not exist, create it.

                        O_EXCL If O_CREAT|O_EXCL is specified, the return value is -1, which means the file exists.

                        O_APPEND Adding this parameter can make every written thing wrap and write to the next line.

                        O_TRUNC Add this parameter to clear the previous content and rewrite the latest content

The use of the open() function depends on the application scenario to decide which one to use. If the file exists, use the first one. If it does not exist, use the second one. O_CREAT (such as O_RDWR|O_CREAT) needs to be used in the flag, and the mode record band Created file access permissions. File access permissions are generally read and write (0600)

return value:

Open successfully: return an integer

Open failed: return -1

close()

head File:  

       #include <unistd.h>

Function prototype:

      int close(int fd);

Function: Close an open file.

Parameter Description:

                fd is the file descriptor returned by the open function.

return value:

Close successfully: return 0

Close failed: return -1

Note: Open files must be closed, otherwise a large number of resources will be occupied, resulting in insufficient memory.

write()

Header file :

       #include <unistd.h>

Function prototype

       ssize_t write(int fd, const void *buf, size_t count);

Function: Write content to the file pointed to by fd. The vernacular explanation is to take the count bytes of data placed in the buffer buf and write it to the open file.

Parameter description :

                1.int fd

                       File descriptor, the number returned by the open function after it is successfully opened.

                2.const void *buf

                        An untyped pointer, the buffer is used to store the content you want to write.

                3.size_t count

                        The number of bytes to write to the file, and how many bytes to write the buffer data to.

                        You can use sizeof and strlen to find the size of the buffer. Sizeof calculates the size of the buf pointer, and strlen calculates the size of the string in the entire buf.

Return value :

Writing successfully: Returns an integer, which is the number of bytes written

Write failed: return -1

read()   

Header file :

         #include <unistd.h>

Function prototype :

        ssize_t read(int fd, void *buf, size_t count);

 Function: Read the content from the file pointed to by fd. The vernacular explanation is to read count bytes of data from the file pointed to by fd and store it in buf.

Note: When defining buf, pay attention to the problem of wild pointers and open up space for buf.

Parameter description :  

                1.int fd

                       File descriptor, the number returned by the open function after it is successfully opened.

                2.const void *buf

                        An untyped pointer, the buffer is used to store the content you want to read.

                3.size_t count

                        Read the number of bytes of the file and store the number of bytes of data in the file in the buffer.

Return value :

Read successfully: Return the number of bytes read (the return value for blank files is 0)

Read failed: return value is -1

Read function problem : When reading a file, make sure the cursor of the file is at the first position, otherwise the read will be blank. Explain it here:

Assuming that the above content is written to a blank file, the cursor of the file will reach f. When reading, the reading starts from behind the cursor, so the read content will be blank. This cursor is similar to the one that flashes after typing in a word document.

Solution:

                1. Reopen. After successful writing, close the file and then open the file to move the cursor to the first position.
                          

                                close(fd);

                          fd = open("./file1",O_RDWR);

                2. Reposition the cursor. Use the lseek function to reposition the cursor.

                  lseek(int fd, offset, int whence);

                     1.文件:  #include <sys/types.h>
                                     #include <unistd.h>

                      2. Parameter description: fd: file descriptor

                                          offset: offset value (positive numbers move the cursor backward, negative numbers move forward) relative to the offset of the cursor position

                                          int whence: cursor position, which has three types:

                                                                  SEEK_SET cursor points to the head,

                                                                  SEEK_CUR cursor points to the current position,

                                                                   SEEK_ENDThe cursor points to the end                                  

lseek(fd,0,SEEK_SET)指到文件头
lseek(fd,0,SEEK_END)指到文件尾
lseek(fd,-17,SEEK_CUR)复数往前移,正数往后移

                      3. The lseek function can cleverly calculate the size of the file content: the return value of lseek is the offset value of the header.         

 int filesize = lseek(fd,0,SEEK_END);

creat()

Header file :

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

Function prototype         

      int creat(const char *pathname, mode_t mode);

Function description: Create a file

Parameter description :

                  1.const char *pathname The storage path of the created file

                  2.mode_t mode gives permissions to the created files. You can use a few

                      宏表示        数字
					 S_IRUSR         4         可读
					 S_IWUSR         2         可写  
					 S_IXUSR         1         可执行	
					 S_IRWXU         7         可读、写、执行

Return value :

                Returns the file descriptor fd for this file.

Guess you like

Origin blog.csdn.net/qq_44848795/article/details/121844381