文件系统(下)

今天写的东西,在我很早之前就写过了。我就简单写段代码来讲解,巩固一下知识。


1.lseek

off_t lseek(int fd,off_t mov,int pos);
fd : 为文件描述符
mov : 为文件的偏移位置 正为向后操作,负为向前操作
该函数成功返回当前位置,其实就是返回
pos : 文件开始操作的位置
		SEEK_SET 	//起始
		SEEK_CUR	//当前
		SEEK_END	//末尾
文件操作时,其文件位置会自动发生偏移。
#include <stdio.h>
#include <fcntl.h>

int main(){
    int fd = open("test.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd == -1){
        perror("open");
        return -1;
    }
    char *str = "hello world!";
    int res = write(fd, str, strlen(str));
    if(res == -1){
        perror("write");
        return -1;
    }
    int pos = lseek(fd, 0, SEEK_CUR);
    printf("pos : %d\n",pos);

    pos = lseek(fd, -2, SEEK_CUR);
    res = write(fd, "ZZ", 2);
    printf("pos : %d\n",pos);

    pos = lseek(fd, 0, SEEK_CUR);
    printf("pos : %d\n",pos);



    close(fd);
    return 0;
}

输出

pos : 12
pos : 10
pos : 12

2.fcntl

fcntl简单使用(之前的博客,还有文件锁的使用范例)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值