gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:56:07 28 4
gpt4 key购买 nike

我正在尝试使用 MMAP 和 MEMCPY 将文件从 A 复制到 B。下面的代码正是这样做的,但是当我使用 CMP 比较 block 时,它说“mem_copy.c dest differ: byte 1, line 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;
}

最佳答案

明白了。

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

关于c - mmap,memcpy 将文件从 A 复制到 B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582920/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com