我今天一直在 VC++ 2008 上玩内存映射,但我仍然没有完全理解如何使用它,或者它是否适合我的目的。我的目标是快速读取一个非常大的二进制文件。
我有一个结构:
typedef struct _data
{
int number;
char character[512];
float *entries;
}Data;
它被多次写入文件。“条目”变量是浮点小数数组。写完这个文件(10000 个数据结构,每个“条目”数组是 90000 个浮点数)后,我尝试使用以下函数对这个文件进行内存映射,以便我可以更快地读取数据。这是我到目前为止所拥有的:
void readDataMmap(char *fname, //name of file containing my data
int arraySize, //number of values in struct Data
int entrySize) //number of values in each "entries" array
{
//Read and mem map the file
HANDLE hFile = INVALID_HANDLE_VALUE;
HANDLE hMapFile;
char* pBuf;
int fd = open(fname, O_RDONLY);
if(fd == -1){
printf("Error: read failed");
exit(-1);
}
hFile = CreateFile((TCHAR*)fname,
GENERIC_READ, // open for reading
0, // do not share
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (hFile == INVALID_HANDLE_VALUE)
{
printf("First CreateFile failed"));
return (1);
}
hMapFile = CreateFileMapping(hFile,
NULL, // default security
PAGE_READWRITE,
0, // max. object size
0, // buffer size
NULL); // name of mapping object
if(hMapFile == ERROR_FILE_INVALID){
printf("File Mapping failed");
return(2);
}
pBuf = (char*) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_READ, // read/write permission
0,
0,
0); //Was NULL, 0 should represent full file bytesToMap size
if (pBuf == NULL)
{
printf("Could not map view of file\n");
CloseHandle(hMapFile);
return 1;
}
//Allocate data structure
Data *inData = new Data[arraySize];
for(int i = 0; i<arraySize; i++)inData[i].entries = new float[entrySize];
int pos = 0;
for(int i = 0; i < arraySize; i++)
{
//This is where I'm not sure what to do with the memory block
}
}
在函数结束时,在内存被映射并且我返回一个指向内存块“pBuf”开头的指针之后,我不知道该怎么做才能将该内存块读回我的数据中结构体。所以最终我想把这块内存转移回我的 10000 个数据结构条目的数组中。当然,我这样做可能完全错了......