【发布时间】:2012-10-08 23:20:01
【问题描述】:
我今天一直在 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 个数据结构条目的数组中。当然,我这样做可能完全错了……
【问题讨论】:
-
将指针写入文件通常没有意义。文件内容的实际格式是什么?
-
@Harry Johnston:文件内容是二进制数据结构集
-
所以实际的浮点数不在文件中的任何地方?你能告诉我们用于编写文件的代码吗?
-
不要尝试在类/结构中使用
memcpy,因为允许编译器在成员之间添加填充,这会搞砸事情。还要记住多字节数量的字节序。更有理由从缓冲区/内存中单独分配结构成员。
标签: c++ windows memory-mapping