linux——文件光标移动(lseek)

 SEEK_SET: 光标在文件的头位置。

SEEK_CUR:当前光标位置。

SEEK_END:光标文件的尾巴位置。

off_t offset   : 偏移值。

代码:

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


int main()
{
   int fd;
   char *buf = "qianrushi";

   fd = open("./file1",O_RDWR);
   if(fd == -1)
   {
        printf("open file1 failed\n");
        fd = open("./file1",O_RDWR|O_CREAT,0600);
        if(fd>0){

                printf("create file1 successful\n");
        }
   }
        printf("open success : fd=%d\n",fd);
        int n_write = write(fd,buf,strlen(buf));
        if(n_write != -1)
        {
                printf("write %d byte to file\n",n_write);
        }

        char *readBuf;
        readBuf = (char *)malloc(sizeof(char)*n_write+1);
        lseek(fd,0,SEEK_SET);              //将光标位置从新置于文件头位置   
        int n_read = read(fd,readBuf,n_write);
        printf("read %d,context:%s\n",n_read,readBuf);
        close(fd);

        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux文件编程中,可以使用lseek函数来重置文件光标的位置。lseek函数的原型如下: ``` off_t lseek(int fd, off_t offset, int whence); ``` 其中,fd是文件描述符,用于标识打开的文件;offset是偏移量,用于指定光标相对于whence参数的偏移量;whence是参考位置,可以是以下值之一: - SEEK_SET:从文件起始位置开始计算偏移量。 - SEEK_CUR:从当前光标位置开始计算偏移量。 - SEEK_END:从文件末尾位置开始计算偏移量。 通过调用lseek函数,可以将文件光标重新定位到指定位置。在示例代码中,通过调用lseek(fd,0,SEEK_SET)将文件光标重置到文件起始位置。这样就可以在重置光标后从指定位置继续读取文件内容。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Linux文件编程之标准C库](https://blog.csdn.net/weixin_45637109/article/details/129930976)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Linux系统编程之文件篇](https://blog.csdn.net/woweiwang007/article/details/129160046)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值