能够实现文件拓展的两个函数
lseek与truncate
1.lseek函数声明
1 #include <sys/types.h>
2 #include <unistd.h>
3
4 off_t lseek(int fd, off_t offset, int whence);
函数使用说明:
参数1:文件描述符
参数2:光标需要移动的位置,正数后移,负数前移
参数3:对应三个宏
1、SEEK_SET == 0 设置光标位置
2、SEEK_CUR == 1 获取当前位置
3、SEEK_END == 2 文件末尾位置
返回值:成功返回当前光标的位置,失败返回-1,失败信息会保存在errno中。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。文件拓展功能实现代码:
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 //如果不执行一次写操作 不会拓展成功
21 write(fd, "1", 1); 22
23 return 0; 24 }
2.truncate函数声明
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);
函数使用说明:
truncate:
参数1:文件名
参数2:文件最终大小
ftruncate:
参数1:文件描述符
参数2:文件最终大小
返回值:成功返回当前光标的位置,失败返回-1,失败信息会保存在errno中。
文件拓展功能实现代码:
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 }

更多精彩