#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
int main(int argc, char* argv[]){
struct stat sb;
off_t len;
char *fp;
int fd;
if (argc < 2){
fprintf(stderr, "usage: %s file1 [file2...]\n", argv[0]);
exit(1);
}
for (int i = 1; i < argc; ++i)
{
fd = open (argv[i], O_RDONLY);
if(fd == -1){
perror("open");
exit(2);
}
if (fstat (fd, &sb) == -1){
perror("fstat");
exit(3);
}
if(!S_ISREG (sb.st_mode)){
fprintf(stderr, "%s is not a file\n", argv[i]);
exit(4);
}
fp = mmap (0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (fp == MAP_FAILED){
perror("mmap");
exit(5);
}
if (close(fd) == -1){
perror("close");
exit(6);
}
write(STDOUT_FILENO, fp, sb.st_size);
putchar('\n');
if(munmap (fp, sb.st_size)==-1){
perror("munmap");
exit(7);
}
}
}
Comments