[Linux文件]使用lseek函数的偏移量来分次写入数据的实例
//这是一个使用lseek在一个文件中连续写入字符串的应用#include<fcntl.h>#include<stdio.h>#include<string.h>intmain(intargc,char*argv[]){inttemp,seektemp,i,j;intfd;//文件描述符charwritebuf[17]="thisisatest!\n";//字符串最后加上回车换行if(argc!=2)//如果参数错误{printf("Plzinputthecorrcetfilenameas'./exam309lseekFunfilenamestring'!\n");return1;//如果参数不正确则退出}fd=open(*(argv+1),O_RDWR|O_CREAT,S_IRWXU);//打开文件如果没有则创建temp=write(fd,writebuf,sizeof(writebuf));//写入数据seektemp=lseek(fd,0,SEEK_CUR);//获得当前的偏移量for(i=0;i<10;i++)//连续写入10个字符串{j=sizeof(writebuf)*(i+1);//计算下一次的偏移量seektemp=lseek(fd,j,SEEK_SET);temp=write(fd,writebuf,strlen(writebuf));//写入数据}close(fd);//关闭文件return0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。