我所做的:以相反的顺序复制文件的内容。我不能做的是:将内容复制到正向。
我在网上做了研究,我发现lseek()有这样的论点。
lseek(file_descriptor,offset,whence);对于反向阅读,逻辑是直接的。我的代码如下:
#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));
}
} 我认为可以对正向复制文件进行哪些更改。
count=0;
lseek(fd,count,0)!=-1
but this is taking the program in infinite loop . need help .发布于 2012-12-03 21:55:04
要向前复制,您不需要lseek。
您只需要在read返回零之前进行复制:
while(read(fd,&buffer,sizeof(char)) > 0)
{
write(fd1,&buffer,sizeof(char));
}当然,为了有效地执行此操作,您将使用一个大于一个字符的缓冲区,但如果最后一个read小于缓冲区,则必须小心write多少数据。
发布于 2012-12-03 21:52:50
您的向后复制依赖于count变为负值并且查找失败。这不适用于正偏移量,因为lseek(2)允许设置超出文件末尾的偏移量,请参阅手册页。
https://stackoverflow.com/questions/13684557
复制相似问题