Two functions that can implement file expansion

lseek与truncate

1.lseek function declaration

1 #include <sys/types.h>
2 #include <unistd.h>
3 
4 off_t lseek(int fd, off_t offset, int whence);

Function usage instructions:

Parameter 1: File descriptor
Parameter 2: The position where the cursor needs to move, positive numbers move backward, negative numbers move forward
Parameter 3: Corresponding to three macros

   1、SEEK_CUR  ==  0

   2、SEEK_CUR  ==  1

   3、SEEK_END  ==  2

Return value: The current cursor position is returned successfully, and -1 is returned if it fails, and the failure information will be saved in errno.

File extension function implementation code:

 1 #include <stdio.h>
 2 #include <sys/types.h>
 3 #include <sys/stat.h>
 4 #include <fcntl.h>
 5 #include <stdlib.h>
 6 #include <string.h>
 7 #include <unistd.h>
 8 
 9 int main(void)
10 {
11     int fd = open("buf.txt", O_RDWR);
12     if (fd == -1)
13     {
14         perror("open");
15          exit(- 1 );
 16      }
 17      
18      int len ​​= lseek(fd, 10 , SEEK_END);
 19      
20      // If a write operation is not performed, the expansion will not succeed 
21      write(fd, " 1 " , 1 );
 22      
23      return  0 ;
 24 }

 

2. truncate function declaration

1 #include <unistd.h>
2 #include <sys/types.h>
3 
4 int truncate(const char *path, off_t length);
5 int ftruncate(int fd, off_t length);

Function usage instructions:

truncate:

  Parameter 1: file name

  Parameter 2: The final size of the file

ftruncate

  Parameter 1: file descriptor

  Parameter 2: The final size of the file

Return value: The current cursor position is returned successfully, and -1 is returned if it fails, and the failure information will be saved in errno.

File extension function implementation code:

 1 #include <stdio.h>
 2 #include <sys/types.h>
 3 #include <stdlib.h>
 4 #include <unistd.h>
 5 
 6 int main(void)
 7 {
 8     int fd = open("buf.txt", O_RDWR);
 9     if (fd == -1)
10     {
11         perror("open");
12         exit(-1);
13     }
14     
15     ftruncate(fd, 100);
16     //truncate("buf.txt", 100);
17     
18     return 0;
19 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325882471&siteId=291194637