系统调用 6--lseek

本文通过一个简单的C程序示例介绍了如何使用lseek和read这两个Linux系统调用。程序首先打开一个文件,然后使用lseek将文件指针定位到指定位置,并使用read从该位置读取一定数量的字节到缓冲区中。本文适用于希望了解这些基本文件操作的初学者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



/*********************
*file: lseek.c
*author:QG
*time:2015-05-11
*description:
**********************/

int main()
{
    char *in = "./123.txt";
    //char *in = "1234567890abcdefghijklmnopqrstuvwxyz";
    char buf[10];

    int a = 0;
    int c = 0;
    int d = 0;
    a = open(in,O_RDWR|O_CREAT,0755);
    if(a < 0)
    {
        printf("open in fail!\n");
    }
    else if(a > 0)
    {
        printf("open in OK,descriptor is %d!\n",a);
    }

    c = lseek(a,4,SEEK_SET);
    if(c < 0)
    {
        printf("lseek fail!\n");
    }
    else if(c > 0)
    {
        printf("lseek is OK,location is %d bytes from in!\n",c);
    }
    d = read(a,buf,3);
    buf[3]='\0'; 
    if(d < 0)
    {
        printf("read fail!\n"); 
    }
    else if(d > 0)
    {
        printf("read is OK,read %d bytes from in!\n",d);
        printf("read buf :%s!\n",buf);
    }

    return(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值