try to make build portable: remove SDL_mixer dependency, remove -f from cp command...
[openc2e.git] / mmapifstream.cpp
blobb37d1f1b35ad6cfd8a0fd106b797ab95eba4af04
1 /*
2 * mmapifstream.cpp
3 * openc2e
5 * Created by Alyssa Milburn on Sat Jul 24 2004.
6 * Copyright (c) 2004 Alyssa Milburn. All rights reserved.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
20 #include "mmapifstream.h"
21 #include "openc2e.h"
22 #ifdef _WIN32
23 #include <windows.h>
24 #else // assume POSIX
25 #include <sys/types.h>
26 #include <sys/mman.h>
27 #endif
28 #include <iostream> // debug needs only
30 mmapifstream::mmapifstream(std::string filename) {
31 live = false;
32 mmapopen(filename);
35 void mmapifstream::mmapopen(std::string filename) {
36 open(filename.c_str(), std::ios::binary);
37 if (!is_open()) return;
39 #ifdef _WIN32
40 // todo: store the handle somewhere?
41 HANDLE hFile = CreateFileA(filename.c_str(), GENERIC_READ, FILE_SHARE_READ,
42 NULL, OPEN_EXISTING, 0, NULL);
43 HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
44 void *mapr = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
45 #else
46 FILE *f = fopen(filename.c_str(), "r");
47 assert(f);
48 /* if (!f) {
49 close();
50 setstate(failbit);
51 perror("fopen");
52 return;
53 } */
55 // now do the mmap (work out filesize, then mmap)
56 int fno = fileno(f);
57 seekg(0, std::ios::end);
58 filesize = tellg();
59 assert((int)filesize != -1);
60 seekg(0, std::ios::beg);
62 void *mapr = mmap(0, filesize, PROT_READ, MAP_PRIVATE, fno, 0);
63 fclose(f); // we don't need it, now!
64 #endif
66 assert(mapr != (void *)-1);
67 map = (char *)mapr;
68 live = true;
71 mmapifstream::~mmapifstream() {
72 if (live)
73 #ifdef _WIN32
74 UnmapViewOfFile(map);
75 #else
76 munmap(map, filesize);
77 #endif
79 /* vim: set noet: */