Programming Language: C Follow the instruction. The code runs but not sure if it
ID: 3856864 • Letter: P
Question
Programming Language: C
Follow the instruction. The code runs but not sure if it functions as the instruction intended, help us out on that.
Additionally, what commands do we need to enter in terminal? Do we need extra files? ./test filename doesn't seem to work as there is no output.
Instruction
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.
Source Code (help us fix if there are error)
#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);
}
}
Explanation / Answer
When i am compailing the code I got to know that these are the mistakes you are doing please Check the below changes.
/temp/file.cpp: In function ‘int main(int, char**)’:
/temp/file.cpp:13:44: error: ‘strcmp’ was not declared in this scope
if (argc != 2 || strcmp(argv[1], "—help") == 0) {
^
/temp/file.cpp:28:13: error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
Hope this will helps you Thank you have a great day!!1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.