能够实现文件拓展的两个函数

本文详细介绍了lseek和truncate函数的使用方法及参数含义,并通过示例代码展示了如何利用这两个函数来改变文件的大小和光标位置。

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中。

文件拓展功能实现代码:

 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 }

 

转载于:https://www.cnblogs.com/SingleJourney/p/9008162.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值