Skip to content

Instantly share code, notes, and snippets.

@braydonf
Last active April 11, 2017 09:32
Show Gist options
  • Save braydonf/c865536290e3ff59158ab3023a9a331a to your computer and use it in GitHub Desktop.
Save braydonf/c865536290e3ff59158ab3023a9a331a to your computer and use it in GitHub Desktop.
testing memory mapped files
#include <stdio.h>
#include <errno.h>
#include <stdint.h>
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#else
#include <sys/mman.h>
#endif
int unmap_file(uint8_t *map, uint64_t filesize)
{
#ifdef _WIN32
if (!FlushViewOfFile(map, filesize)) {
return GetLastError();
}
if (!UnmapViewOfFile(map)) {
return GetLastError();
}
#else
if (munmap(map, filesize)) {
return errno;
}
#endif
return 0;
}
int map_file(int fd, uint64_t filesize, uint8_t **map)
{
int status = 0;
#ifdef _WIN32
HANDLE fh = (HANDLE)_get_osfhandle(fd);
if (fh == INVALID_HANDLE_VALUE) {
return EBADF;
}
HANDLE mh = CreateFileMapping(fh, NULL, PAGE_READWRITE, 0, 0, NULL);
if (!mh) {
status = GetLastError();
goto win_finished;
}
*map = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, filesize, NULL);
if (!*map) {
status = GetLastError();
goto win_finished;
}
win_finished:
CloseHandle(mh);
CloseHandle(fh);
return status;
#else
*map = (uint8_t *)mmap(NULL, filesize, PROT_READ, MAP_SHARED, fd, 0);
if (*map == MAP_FAILED) {
status = errno;
}
return status;
#endif
}
int main()
{
FILE *fp = fopen("video.ogv", "r+");
int fd = fileno(fp);
if (!fp) {
printf("failed open.\n");
return 1;
}
fseek(fp, 0L, SEEK_END);
uint64_t filesize = ftell(fp);
rewind(fp);
printf("filesize: %lu\n", filesize);
uint8_t *zero = NULL;
int error = map_file(fd, filesize, &zero);
if (error) {
printf("failed w/ code: %d\n", error);
return error;
}
printf("value: %i\n", zero[40001]);
error = unmap_file(zero, filesize);
if (error) {
printf("failed to unmap file: %d", error);
return error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment