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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With