Reputation: 1650
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(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 .
Upvotes: 0
Views: 1376
Reputation: 25599
To copy in the forward direction you do not need lseek
.
You need only copy until read
returns zero:
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.
Upvotes: 1
Reputation: 84239
Your backwards copy relies on the count
becoming negative and seek failing.
This doesn't work for positive offset since lseek(2)
allows the offset to be set beyond the end of the file, see the manual page.
Upvotes: 0