【Linux系统编程】15.fcntl、lseek、truncate

目录

fcntl

lseek

参数fd

参数offset

参数whence

返回值

应用场景

测试代码1

测试结果

测试代码2

测试结果

查看文件方式

truncate

参数path

参数length

测试代码3  

测试结果

fcntl

获取文件属性、修改文件属性。

int flgs=fcntl(fd,F_GETFL);		//获取
flgs|=O_NONBLOCK;		//修改
fcntl(fd,F_SETFL,flgs);		//设置
  • F_GETFL:获取文件状态

  • F_SETFL:设置文件状态

lseek

man 2 lseek

参数fd

文件描述符。

参数offset

偏移量。

参数whence

起始偏移位置。SEEK_SET、SEEK_CUR、SEER_END。

返回值

  • 成功:较起始位置偏移量。

  • 失败:-1。

应用场景

  1. 文件的“读”、“写”使用同一偏移位置

  2. 使用lseek获取文件大小。

  3. 使用lseek拓展文件大小。想要文件的大小真正拓展,必须引起IO操作。也可以使用truncate函数,直接拓展文件。

测试代码1

获取文件大小。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc,char *argv[]){
    int fd=open(argv[1],O_RDWR);
    if(fd==-1){
        perror("open error");
        exit(1);
    }
    int Long=lseek(fd,0,SEEK_END);
    printf("Long=%d\n",Long);
    return 0;
}

测试结果

测试代码2

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int fd = open(argv[1], O_RDWR);
    if (fd == -1)
    {
        perror("open error");
        exit(1);
    }
    int Long = lseek(fd,10, SEEK_END);		//在内容末尾偏移10个字节
    write(fd, "aaa", 3);	//追加“aaa”
    close(fd);
    return 0;
}

测试结果

 

 ^@:文件空洞

查看文件方式

查看文件的16进制表示形式。

od -tcx 文件名
od -tcx a1.txt

 查看文件的10进制表示形式。

od -tcd 文件名
od -tcd a1.txt

truncate

拓展文件大小。而且只能拓展现有文件的大小。

man 2 truncate

参数path

现有的文件或者文件路径。

参数length

拓展文件到的大小。

测试代码3  

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int flag = truncate("a1.txt", 300);
    printf("flag:%d\n", flag);
    return 0;
}

测试结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

因心,三人水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值