简体   繁体   English

lseek()用于复制文件

[英]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多少数据。

Your backwards copy relies on the count becoming negative and seek failing. 向后复制依赖于count变为负数并寻求失败。 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. 这不适用于正偏移量,因为lseek(2)允许将偏移量设置为超出文件末尾,请参见手册页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM