File: mapfile.cpp

package info (click to toggle)
sdcv 0.3.4-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,644 kB
  • ctags: 1,207
  • sloc: sh: 9,235; ansic: 7,803; cpp: 2,613; makefile: 485; yacc: 316; sed: 16
file content (93 lines) | stat: -rw-r--r-- 2,102 bytes parent folder | download
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif


#ifdef HAVE_MMAP
# include <unistd.h>
# else
# ifndef _WIN32
#  include <glib.h>
# endif
#endif

#include "mapfile.h"


bool TMapFile::open(const char *file_name)
{
#ifdef HAVE_MMAP
  if((mmap_fd = ::open(file_name, O_RDONLY ))<0){
    //g_message("Open file %s failed!\n",idxfilename);
    return false;
  }
  struct stat info;
  fstat(mmap_fd, &info);  
  file_size=info.st_size;
  data_buffer = (char *)mmap(NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
  if ((void *)data_buffer == (void *)(-1)) {
    //g_message("mmap file %s failed!\n",idxfilename);
    ::close(mmap_fd);
    data_buffer=NULL;
    return false;
  }
#else
  if(!g_file_get_contents(file_name, &data_buffer, &file_size, NULL))
    return false;
#endif
  return true;
}


bool TMapFile::open(const char *file_name, size_t _file_size)
{
  file_size=_file_size;
#ifdef HAVE_MMAP
  if((mmap_fd = ::open(file_name, O_RDONLY ))<0){
    //g_message("Open file %s failed!\n",idxfilename);
    return false;
  } 
  data_buffer = (char *)mmap(NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
  if ((void *)data_buffer == (void *)(-1)) {
    //g_message("mmap file %s failed!\n",idxfilename);
    ::close(mmap_fd);
    data_buffer=NULL;
    return false;
  }
  
#else
#ifdef _WIN32
  hFile = CreateFile(file_name, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0,  file_size, NULL);
  data_buffer = (gchar *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size);
#else
  if(!g_file_get_contents(file_name, &data_buffer, &file_size, NULL))
    return false;
#endif
#endif
  return true;
}
void TMapFile::close(void)
{
#ifdef HAVE_MMAP
  if(data_buffer){
    munmap(data_buffer, file_size);
    data_buffer = NULL;
    file_size = 0;
    ::close(mmap_fd);
    mmap_fd = -1;
  }
#else
#  ifdef _WIN32
  if(data_buffer){
    UnmapViewOfFile(data_buffer);
    data_buffer = NULL;
    CloseHandle(hFileMap);
    CloseHandle(hFile);
  }
#  else
  g_free(data_buffer);
  data_buffer = NULL;
#  endif
#endif
}