C使用lseek逆序复制文件



我已经知道如何从一开始就将一个文件复制到另一个文件,但是我如何修改程序以反向顺序复制它?源文件应有读访问权限,目标文件应有读写执行。我必须使用文件控制库。

例如

FILE A            File B should be
|---------|        |----------|
|ABCDEF   |        |FEDCBA    |
|---------|        |----------|

* * * * * * * * * * * * * * * * * * * * * 更新 * * * * * * * * * *

谢谢你,MikeNakis的提示和建议你的代码

我已经重新编写了代码,现在它以反向顺序复制字节打印文件大小

代码

#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, char *argv[]) {
    int source, dest, n;
    char buf;
    int filesize;
    int i;
    if (argc != 3) {
        fprintf(stderr, "usage %s <source> <dest>", argv[0]);
        exit(-1);
    }
    if ((source = open(argv[1], 0400)) < 0) { //read permission for user on source
        fprintf(stderr, "can't open source");
        exit(-1);
    }
    if ((dest = creat(argv[2], 0700)) < 0) { //rwx permission for user on dest
        fprintf(stderr, "can't create dest");
        exit(-1);
    }
    filesize = lseek(source, (off_t) 0, SEEK_END); //filesize is lastby +offset
    printf("Source file size is %dn", filesize);
    for (i = filesize - 1; i >= 0; i--) { //read byte by byte from end
        lseek(source, (off_t) i, SEEK_SET);
        n = read(source, &buf, 1);
        if (n != 1) {
            fprintf(stderr, "can't read 1 byte");
            exit(-1);
        }
        n = write(dest, &buf, 1);
        if (n != 1) {
            fprintf(stderr, "can't write 1 byte");
            exit(-1);
        }
    }
    write(STDOUT_FILENO, "DONEn", 5);
    close(source);
    close(dest);

    return 0;
}

查找到末尾,然后从那里开始阅读。难怪它什么也读不出来。您需要查找到末尾减去一个字节,读取一个字节,写入它,然后查找到末尾减去两个字节,读取另一个字节,以此类推。

我认为这是一个家庭作业,所以你的教授应该不会介意这种方法效率极低。(现实世界中的表现问题非常不符合学术。)如果他抱怨,告诉他,在理论上,它与任何其他执行相同任务的算法具有相同的时间复杂度:O(N)。(发音为"big oh of en"。)他会给你A+的。

lseek(source, (off_t) i, SEEK_SET);应该是lseek(source, (off_t) i - 1, SEEK_SET);