#include <stdio.h>
#include <errno.h> //errno
#include <string.h> //strerror()
/* lseek() */
#include <sys/types.h>
#include <unistd.h> //read() write()
/* open() */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
# define PER_IO_BYTES 4096
int main(int argc , char ** argv)
{
char caFile[32] = {'\0'};
strncpy(caFile,argv[1],sizeof(caFile));//复制
// fd = open();
int ret = -1;
strcat(caFile,".old");//就是接上一个.old
ret = rename(argv[1],caFile);
if(-1==ret)
{
printf("rename error:%s\n",strerror(errno));
return -1;
}
int fdNew = -1;
fdNew = open(argv[1],O_WRONLY |O_CREAT,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if(-1==fdNew)
{
printf("open error:%s\n",strerror(errno));
return -1;
}
int fdOld=-1;
fdOld = open(caFile,O_RDONLY);
if(-1==fdOld)
{
printf("open error:%s\n",strerror(errno));
return -1;
}
off_t offset = 0;
printf("请输入位置:\n");
scanf("%ld",&offset);
char caBuf[PER_IO_BYTES] = {'\0'};
int iLeft = offset;
int iReaded = 0;
while(iLeft)
{
if(iLeft >= PER_IO_BYTES)
{
ret = read(fdOld,caBuf,PER_IO_BYTES);
}
else
{
ret = read(fdOld,caBuf,iLeft);
}
if(-1==ret)
{
printf("read error:%s\n",strerror(errno));
break;
}
iLeft -= ret;
ret = write(fdNew,caBuf,ret);
if(-1==ret)
{
printf("write error:%s\n",strerror(errno));
break;
}
}
char *pData = "$$$hljhkjhakfiewu$$$";
ret = write(fdNew,pData,strlen(pData));
if(-1 == ret)
{
printf("write error:%s\n",strerror(errno));
return -1;
}
offset = lseek(fdOld,0,SEEK_CUR);
while(1)
{
ret = read(fdOld,caBuf,PER_IO_BYTES);
if(-1 == ret)
{
printf("read error :%s\n",strerror(errno));
}
else if(0 == ret)
{
break;
}
ret = write(fdNew,caBuf,ret);
if(-1 == ret)
{
printf("write errorp:%s\n",strerror(errno));
break;
}
}
close (fdOld);
close(fdNew);
ret = remove(caFile);
if(-1 == ret)
{
printf("remove error:%s\n",strerror(errno));
return -1;
}
return 0;
}
网友评论