Linux基础——文件编程(Linux中“一切皆文件”(2))

1.光标定位 lseek()函数

1.1函数需包含的头文件:

#include <sys/types.h>
#include <unistd.h>

1.2参数说明

fd:文件描述符
offset:偏移量
whence:位置
SEEK_SET:The offset is set to offset bytes. offset为0时表示文件开始位置。
SEEK_CUR:The offset is set to its current location plus offset bytes. offset为0时表示当前位置。
SEEK_END:The offset is set to the size of the file plus offset bytes. offset为0时表示结尾位置
函数返回值
成功返回当前位置到开始的长度
失败返回-1并设置errno
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUF_MAX 512 /*buf缓冲区最大值*/

/*向中文件写入数据并把写入内容打印到标准输出*/
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        printf("not fount file name");
        return -1;    
    }
    int fd = open(argv[1], O_RDWR | O_CREAT);
    write(fd, "hello linux...", 15);
    /*读写位置在末尾*/
    /*把读写位置移动到文件首部*/
    lseek(fd, 0, SEEK_SET);
    char buf[20];
    memset(buf, 0, sizeof(buf));
    int read_size = read(fd, buf, sizeof(buf));
    if(read_size > 0)
    {
        write(STDOUT_FILENO, buf, read_size);    /*STDIN_FILENO STDERR_FILENO*/
    }
    close(fd);
    return 0;
}

2.关闭 文件close()函数

函数原型:

int close(int fd);

功能描述:用于关闭一个被打开的的文件
所需头文件: #include
函数原型:int close(int fd)
参数:fd文件描述符
函数返回值:0成功,-1出错

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值