如何在C ++中创建FileMapping? [英] How to CreateFileMapping in C++?

查看:110
本文介绍了如何在C ++中创建FileMapping?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编码一个游戏预加载器(一个简单的程序,在启动该程序之前将某些文件[maps]加载到缓存中.有人告诉我使用CreateFileMapping,但我仍不确定是否将其加载到物理或虚拟内存中.

I am coding a game preloader (a simple program that loads certain files [maps] into cache before starting the program. I was told to use CreateFileMapping which I am still unsure whether it loads it into the physical or virtual memory...

无论如何,我将需要加载的文件放在哪里?

Anyway, where would I put what files I need to load?

这是我的代码(实际上是由其他人告诉我使用它的堆栈溢出代码)

Here is my code (actually coded by someone else on stack overflow who told me to use it)

#include <windows.h>
#include <cstdio>

void pf(const char* name) {

HANDLE file = CreateFile(name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if(file == INVALID_HANDLE_VALUE) { printf("couldn't open %s\n", name); return; };

unsigned int len  = GetFileSize(file, 0);

HANDLE mapping  = CreateFileMapping(file, 0, PAGE_READONLY, 0, 0, 0);
if(mapping == 0) { printf("couldn't map %s\n", name); return; }

const char* data = (const char*) MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);

if(data)
{
    printf("prefetching %s... ", name);

    // need volatile or need to use result - compiler will otherwise optimize out whole loop
    volatile unsigned int touch = 0;

    for(unsigned int i = 0; i < len; i += 4096)
        touch += data[i];
}
else
    printf("couldn't create view of %s\n", name);

UnmapViewOfFile(data);
CloseHandle(mapping);
CloseHandle(file);
}

int main(int argc, const char** argv)
{
if(argc >= 2) for(int i = 1; argv[i]; ++i) pf(argv[i]);
return 0;
}

推荐答案

pf函数接受文件路径作为其参数.触摸循环会导致文件(或文件的至少4 KB部分)被加载到物理内存中.

The pf function accepts a file path as its parameter. The touch loop causes the file (or at least 4 KB portions of it) to be loaded into physical memory.

这篇关于如何在C ++中创建FileMapping?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆