I am writing a C program that takes more than one file from the command line and combines them into one output file. If the output file is not given, it is created. I copy the file content by using mmap.
However, when I run the following code, I get "mmap: invalid argument" and I am not sure why.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int argc, char *argv[])
{
int opt, output=0, len;
int fd_o, fd_i;
char *addr=NULL;
struct stat stat_input;
const char *errmsg="Invalid argument:\n";
const char *usage=
"combine to one\n";
while((opt = getopt(argc, argv, "o"))!= -1) {
switch(opt){
case 'o':
output=1;
fd_o=open(argv[argc-1], O_WRONLY|O_CREAT|O_TRUNC, 0644);
if (fd_o == -1){
perror("open");
exit(1);
}
break;
case '?':
write(2, errmsg, strlen(errmsg));
write(2, usage, strlen(usage));
exit(1);
}
}
if (output==0){
write(2, errmsg, strlen(errmsg));
write(2, usage, strlen(usage));
exit(1);
}
for(; optind < argc; optind++){
fd_i=open(argv[optind], O_RDONLY);
if (fd_i == -1){
perror("open");
exit(1);
}
fstat(fd_i, &stat_input);
len=stat_input.st_size;
addr=mmap(0, len, PROT_READ, MAP_SHARED, fd_i, 0);
if (addr == MAP_FAILED) {
close(fd_i);
perror("mmap");
exit(1);
}
write(fd_o, *addr, len);
close(fd_i);
munmap(addr,len);
}
close(fd_o);
}