关于C中文件打开、关闭、读、写操作

1) fseek和lseek

fseek用来获取或者设置文件流(文件指针)的位置。 FILE    *fp;

lseek用来获取或者设置文件指针的位置,  int 类型指针

1.1 用open 和 close 打开、关闭文件,对应用 lseek 操作 int 类型指针,示例:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main() {

    // 扩展文件长度,执行写操作
    int fd = open("hello.txt", O_RDWR);

    if(fd == -1) {
        perror("open");
        return -1;
    }

    // 拓展文件的长度 增加100个字节
    int ret = lseek(fd, 100, SEEK_END);

    if(ret == -1) {
        perror("lseek");
        return -1;
    }

    // lseek仅仅为移动指针
    // 若想真正实现拓展,要写入一个空数据
    write(fd, " ", 1);

    // 关闭文件
    close(fd);

    return 0;
}

1.2 用fopen和 fclose 打开、关闭文件,对应用 fseek操作 FILE   *fp ,示例:

#include
main()
{
  FILE * stream;
  long offset;
  fpos_t pos;
  stream = fopen("/etc/passwd", "r");
  fseek(stream, 5, SEEK_SET);
  printf("offset = %d\n", ftell(stream));
  rewind(stream);
  fgetpos(stream, &pos);
  printf("offset = %d\n", pos);
  pos = 10;
  fsetpos(stream, &pos);
  printf("offset = %d\n", ftell(stream));
  fclose(stream);
}

2 ) 来源说明:

标准C库中的fseek函数。需要包含:

#include <stdio.h>

Linux系统的lseek函数。需要包含:

#include <sys/types.h>
#include <unistd.h>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值