C copy files in reverse order with lseek

I have how to copy one file to another from the very beginning, but how can I change the program to copy it in reverse order? The source file must have read access and a destination file to read read. I have to use file management libraries.

eg

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

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

Thanks, MikeNakis for the tips and suggestions, Sangeeth for your code.

I reworked the code and now it copies bytes in reverse order to print files

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;
}
+5
source share
2 answers

. , . 1 , , , , ..

, , . ( - .) , , ​​ , , : O (N). ( " en".) A +.

+5

lseek (, (off_t) i, SEEK_SET); , lseek (source, (off_t) - 1, SEEK_SET);

0

All Articles