Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c copy files in reverse order using lseek

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;
}
like image 447
mydreamadsl Avatar asked Jan 03 '12 17:01

mydreamadsl


1 Answers

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+.

like image 133
Mike Nakis Avatar answered Sep 21 '22 13:09

Mike Nakis