[英]lseek() for copying files
what i have done : copying the content of file in reverse order. 我做了什么:以相反的顺序复制文件的内容。 what i am nt able to do : copy the content in the forward direction .
我无法执行的操作:向前复制内容。
I made research on the web and I found that lseek()
has this arguments.. 我在网络上进行了研究,发现
lseek()
具有这种观点。
lseek(file_descriptor,offset,whence);
for reverse reading the logic is straight forward . 对于反向读取逻辑是直接的。 And my code is as follows :
我的代码如下:
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
int fd,fd1,count=0;
char ch='y',buffer;
if(argc>3)
{
printf("\nSyntax Error!<try> ./cp source_name destination_name\n");
exit(0);
}
fd=open(argv[1],O_RDWR);
if(fd==-1)
{
printf("\nCan not open source file .. :(\n");exit(0);
}
fd1=open(argv[2],O_RDWR);
if(fd1=!-1)
{
printf("\nDestination file exist , OverWrite (Y/N) :");
scanf("%s",&ch);
}
if(ch=='y'||ch=='Y')
fd1=creat(argv[2],O_RDWR|0666);
else
exit(0);
while(lseek(fd,count,2)!=-1)
{
count--;
read(fd,&buffer,sizeof(char));
write(fd1,&buffer,sizeof(char));
}
}
what changes i thought that could be done for copying the file in forward direction . 我认为可以对向前复制文件进行哪些更改。
count=0;
lseek(fd,count,0)!=-1
but this is taking the program in infinite loop . need help .
To copy in the forward direction you do not need lseek
. 要向前复制,您不需要
lseek
。
You need only copy until read
returns zero: 您只需要复制,直到
read
返回零即可:
while(read(fd,&buffer,sizeof(char)) > 0)
{
write(fd1,&buffer,sizeof(char));
}
Of course, to do it efficiently you would use a buffer larger than one character, but then you have to be careful how much data you write
if the last read
is smaller than the buffer. 当然,要高效地执行此操作,您将使用大于一个字符的缓冲区,但是如果最后一次
read
数据小于缓冲区,则必须注意要write
多少数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.