You declare:
struct stat *sb1;
You use:
stat(argv[1],sb1);
You crash and burn because sb1
is a null pointer (since the variable is defined at file scope, it is initialized with 0).
You need to declare (at file scope):
struct stat sb1;
And then in main()
you can use:
if (stat(argv[1], &sb1) != 0)
...oops...
You'll have to review all uses of sb1
to fix the status change from pointer to object, adding an &
where necessary, and changing ->
to .
where necessary.
mmap() by example
This is a mildly edited version of a function I wrote that uses mmap()
to map a file into memory:
/* Map named file into memory and validate that it is a MSG file */
static int msg_mapfile(const char *file)
{
int fd;
void *vp;
struct stat sb;
if (file == 0)
return(MSG_NOMSGFILE);
if ((fd = open(file, O_RDONLY, 0)) < 0)
return(MSG_OPENFAIL);
if (fstat(fd, &sb) != 0)
{
close(fd);
return(MSG_STATFAIL);
}
vp = mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (vp == MAP_FAILED)
return(MSG_MMAPFAIL);
The MSG_xxxx constants are distinct error numbers applicable to the program it came from. It was only needing to read the file, hence the PROT_READ
; I think you may be OK with that too.