Unix学习笔记------文件IO------使用lseek设置文件当前读写偏移量(即:当前的读写位置)

文件IO------使用lseek设置文件当前读写偏移量(即:当前的读写位置)

 

实例:把my.txt 的文件当前的读写位置向后移动5个字节。

 

 

一.My.txt的文件内容如下:

a)        [root@localhost file1]# catmy.txt

b)        hello world  i am a student of angong colleage

c)        who are you ? please tell me

二.源代码如下:

/*

         实例:

                      设置my.txt文件的当前偏移量

 

*/

 

#include<stdio.h>

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

 

#include<error.h>

int main()

 

{

         //定义一些变量

         int  fd_t;

         int  write_wval;

         intread_rval;

         charbuf[100];

 

         //打开my.txt文件

                   /*

                            那么,如何打开这个文件呢??

                            调用open()系统调用来实现。

                           

                                     如何使用open()函数呢??

                                     ::::::

                                     SYNOPSIS

      #include <sys/types.h>

      #include <sys/stat.h>

       #include <fcntl.h>

 

      int open(const char *pathname, int flags);

      int open(const char *pathname, int flags, mode_t mode);

 

      int creat(const char *pathname, mode_t mode);

 

           

                  

                   */

                   fd_t=open("/home/code/file1/my.txt",O_RDWR,775);

                   //判断是否打开成功

                   if(fd_t<0)

                   {perror("openerror \n");

                   _exit(0);

                   }

                  

                   else

                            printf("thefile decribe is :%d \n",fd_t);

                  

                   //调用lseek 函数

                      int demo_t =lseek(fd_t,5,SEEK_CUR);

                      if(demo_t<0)

                      {

                             perror("lseek error \n");

                             

                      }

         //开始从my.txt中读取内容

            read_rval=read(fd_t,&buf,80);

            buf[99]='\n';

           

            if(read_rval<0)

            perror("read error\n");

            else

            write_wval=write(1,&buf,sizeof(buf));

            if(write_wval<0)

            perror("write error \n");

            else

            printf(" EVERY IS OK! \n");

            return 0;

           

                  

                  

                  

 

}

 

 

运行结果截图:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值