summaryrefslogtreecommitdiff
path: root/src/export/mystdlib.c
blob: b65f63de560185dd53fdc1e799acb9a45d1c135a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "mystdlib.h"

MAP map_file( char *filename, int readonly )
{
  struct stat fstatus;
  MAP    map = (MAP)malloc( sizeof( *map ));

  if( map )
  {
    memset( map, 0, sizeof( *map ));

    if( ( map->fh = open( filename, readonly ? O_RDONLY : O_RDWR ) ) >= 0 )
    {
      fstat( map->fh, &fstatus );
      if( ( map->addr = mmap( NULL, map->size = (size_t)fstatus.st_size,
         PROT_READ | ( readonly ? 0 : PROT_WRITE), (readonly ? MAP_PRIVATE : MAP_SHARED), map->fh, 0) ) == MAP_FAILED )
      {
        fprintf( stderr, "Mapping file '%s' failed\n", filename );
        close( map->fh ); free( map ); map = NULL;
      }
    } else {
      fprintf( stderr, "Couldn't open file: '%s'\n", filename );
      free( map ); map = NULL;
    }
  } else {
    fputs( "Couldn't allocate memory", stderr );
  }

  return map;
}

void unmap_file ( MAP *pMap )
{
  if( !pMap || !*pMap ) return;
  munmap( (*pMap)->addr, (*pMap)->size);
  close( (*pMap)->fh);
  free( *pMap ); *pMap = NULL;
}

int getfilesize( int fd, size_t *size)
{
  struct stat sb;
  if( fstat( fd, &sb )) return -1;
  *size = (size_t)sb.st_size;
  return 0;
}