Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program, analogous to the Unix/Linux cat command, that uses mmap() and w

ID: 3857042 • Letter: W

Question

Write a program, analogous to the Unix/Linux cat command, that uses mmap() and write() system calls (instead of read() or write() ) to copy a source file to the screen. Use fstat() to obtain the size of the input file which can be used to size the required memory mapping.

The statement to write the file contents to STDOUT is

         write (STDOUT_FILENO, addr, sb.st_size);

where

addr is the start of the mapping, gotten from mmap() and,

                  sb.st_size is the size of the mapping returned by fstat() in the

                 sb struct.

Please show the command line to compile the file and run the code and the screenshots

Explanation / Answer

#include <sys/mman.h> // for mmap()
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main (int argc, char * argv[])
{

char *addr;
int fd;
struct stat sb;

if (argc != 2 || strcmp(argv[1], "—help") == 0) {

printf("Usage: %s file ", argv[0]);

fd = open(argv[1], O_RDONLY);
if (fd == -1){
printf("File open fdailed. ");
exit(EXIT_FAILURE);
}

/*
Obtain size of the file and use it to specify
the size of the buffer to be written
*/

if (fstat(fd, &sb) == -1) {
printf("fstat error ");
exit(EXIT_FAILURE);
}

addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

if (addr == MAP_FAILED) {
printf("mmap failed ");
exit (EXIT_FAILURE);
}

if (write(STDOUT_FILENO, addr, sb.st_size) != sb.st_size) {
printf("Failed write ");
}

exit(EXIT_SUCCESS);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote