Question: Write your code to make a copy program using memory mapping APIs: Your program should take two arguments from the user. The first is the
Write your code to make a copy program using memory mapping APIs:
-
Your program should take two arguments from the user. The first is the file name for the file to copy from, and the second is the file name where the contend of the first file will be copied to
-
Open the first file with read only option
-
Find the size of the first file
-
Mapp the first file to memory (the whole file)
-
Create the second file with the name as the second argument
-
Use the write() function to write the mapped first file to the second file (note: the buff parameter is the mapped memory for first file)
-
Unmap the first file
-
Close the first file
-
Close the second file.
Below are two sample codes to help get an idea of what kind of code is needed:
//Copy.c
#include //#include #include #include #include #include
int main(int argc, char *argv[]) { struct stat sb; off_t len; char *p; int fd; if(argc fprintf(stderr, "usage: %s ", argv[0]); return 1; } fd = open(argv[1], 0); if(fd == -1){ perror("open"); return 1; }
if(fstat(fd, &sb) == -1){ perror("fstat"); return 1; } if(!S_ISREG(sb.st_mode)){ fprintf(stderr, "%s is not a file ", argv[1]); return 1; } p = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); if(p == MAP_FAILED){ perror("mmap"); return 1; } if(close(fd) == -1) { perror("close"); return 1; } for(len = 0; len putchar(p[len]); } if(munmap(p, sb.st_size) == -1) { perror("muumap"); return 1; } return 0; }
//MappingSample.c
#include //#include #include #include #include #include
int main(int argc, char *argv[]) { struct stat sb; off_t len; char *p; int fd; if(argc fprintf(stderr, "usage: %s ", argv[0]); return 1; } fd = open(argv[1], 0); if(fd == -1){ perror("open"); return 1; }
if(fstat(fd, &sb) == -1){ perror("fstat"); return 1; } if(!S_ISREG(sb.st_mode)){ fprintf(stderr, "%s is not a file ", argv[1]); return 1; } p = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0); if(p == MAP_FAILED){ perror("mmap"); return 1; } if(close(fd) == -1) { perror("close"); return 1; } for(len = 0; len putchar(p[len]); } if(munmap(p, sb.st_size) == -1) { perror("muumap"); return 1; } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
