mmap,memcpy将文件从A复制到B

时间:2014-10-27 07:39:05

标签: c

我正在尝试使用MMAP和MEMCPY将文件从A复制到B.下面的代码正是如此,但是当我使用CMP来比较块时,它说“mem_copy.c dest不同:字节1,第1行,我不知道为什么。”

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

1 个答案:

答案 0 :(得分:9)

知道了。

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