我一直在今天玩弄内存映射在VC++ 2008和我还没有完全了解如何使用它,或者如果它是我的目的是正确的。我的目标是快速读取非常大的二进制文件。读取数据的存储器映射块放入结构
我有一个结构:
typedef struct _data
{
int number;
char character[512];
float *entries;
}Data;
这是写很多很多次到文件中。 “entries”变量是一个浮点小数数组。在写入这个文件(10000个数据结构,每个“entries”数组是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个数据结构项的数组中。当然,我可能会这样做是完全错误的......
将指针写入文件通常没有意义。文件内容的实际格式是什么? –
@哈里约翰斯顿:该文件的内容是二进制数据结构集 – foboi1122
所以实际的浮动不在任何地方的文件?你能告诉我们用于写入文件的代码吗? –