Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mmap, memcpy to copy file from A to B

Tags:

c

I'm trying to copy a file from A to B using MMAP and MEMCPY. The code below does exactly that but when I use CMP to compare the blocks, it says that "mem_copy.c dest differ: byte 1, line 1, and I'm not sure why.

int main(int argc, char **argv){

    int sfd, dfd;
    char *src, *dest;
    struct stat s;

    /* SOURCE */
    sfd = open("hello.c", O_RDONLY);
    fstat(sfd, &s); // st_size = blocksize

    printf("%d\n", (int)s.st_size);

    src = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, sfd, 0);

    /* DESTINATION */
    dfd = open("dest", O_RDWR | O_CREAT, 0666);

    ftruncate(dfd, s.st_size;

    dest = mmap(NULL, s.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, dfd, 0);

    /* COPY */

    memcpy(dest, src, s.st_size);

    munmap(src, s.st_size);
    munmap(dest, s.st_size);

    close(sfd);
    close(dfd);

   return 0;
}
like image 737
Bob Jane Avatar asked Oct 27 '14 07:10

Bob Jane


1 Answers

Got it.

int main(int argc, char **argv){

    int sfd, dfd;
    char *src, *dest;
    size_t filesize;

    /* SOURCE */
    sfd = open("hello.c", O_RDONLY);
    filesize = lseek(sfd, 0, SEEK_END);

    src = mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, sfd, 0);

    /* DESTINATION */
    dfd = open("dest", O_RDWR | O_CREAT, 0666);

    ftruncate(dfd, filesize);

    dest = mmap(NULL, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, dfd, 0);

    /* COPY */

    memcpy(dest, src, filesize);

    munmap(src, filesize);
    munmap(dest, filesize);

    close(sfd);
    close(dfd);

    return 0;
}
like image 110
Bob Jane Avatar answered Nov 07 '22 13:11

Bob Jane