Mmap, memcpy to copy file from A to B

I am 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 blocks it says "mem_copy.c dest is different: 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;
}

      

+3


source to share


1 answer


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;
}

      

+7


source







All Articles