c copy files in reverse order using lseek

北战南征 提交于 2019-12-07 06:27:19

问题


I've got how to copy one file to another from start, but how could i modify the programme to copy it in reverse order? Source file should have read access and destination file read write execute. I have to use file control libraries.

for example

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

*********************UPDATE**********

Thank you, MikeNakis for hints and suggestions ,Sangeeth for your code

I've reworked the code and now it is copy bytes in reverse order printing filesize

here is the code

#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 %d\n", 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, "DONE\n", 5);
    close(source);
    close(dest);



    return 0;
}

回答1:


You just seek to the end and start reading from there. No wonder it won't read anything. You need to seek to the end minus 1 byte, read one byte, write it, then seek to the end minus two bytes, read another byte, and so on.

I presume this is a homework assignment, so your professor should not mind the extreme inefficiency of this approach. (Real-world performance concerns are oh-so un-academic.) If he complains, tell him that in theory, it has the same time complexity as any other algorithm which would perform the same task: O(N). (That's pronounced "big oh of en".) He will give you an A+.




回答2:


lseek(source, (off_t) i, SEEK_SET); should probably be lseek(source, (off_t) i - 1, SEEK_SET);



来源:https://stackoverflow.com/questions/8716113/c-copy-files-in-reverse-order-using-lseek

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!