本人的程序要读取10M左右自定义格式的文件(打开文件后全部读入相应的变量保存),起初我直接用CFile打开文件,用CFile::Read分别读取文件中的内容,估计把文件读取完需8秒。感觉时间比较慢,后改用如下方式 CFile和CMemFile相结合的方式读取,结果所需时间多了很多,令人费解,请高手帮助。
1.CFile方式
CFile file;
file.Open(strFile,CFile::shareDenyNone,NULL); file.Read((unsigned char *)&m_xd,sizeof(double));
file.Read((unsigned char *)&m_yd,sizeof(double));
file.Read((unsigned char *)&m_a,sizeof(double));
file.Read((unsigned char *)&m_k,sizeof(double));
file.Read((unsigned char *)&l0,sizeof(double));
file.Read((unsigned char *)&maxScaleNum,sizeof(int));
......(多条读取语句,及其他语句) 2. CFile和CMemFile相结合的方式
CFile file;
CMemFile memFile;
file.Open(strFile,CFile::shareDenyNone,NULL); DWORD length = file.GetLength();
BYTE* buffer= new BYTE[length];
file.Read(buffer,length);
memFile.Attach(buffer,length,0);
memFile.SetLength(length);
memFile.Read((unsigned char *)&m_xd,sizeof(double));
memFile.Read((unsigned char *)&m_yd,sizeof(double));
memFile.Read((unsigned char *)&m_a,sizeof(double));
memFile.Read((unsigned char *)&m_k,sizeof(double));
memFile.Read((unsigned char *)&l0,sizeof(double));
memFile.Read((unsigned char *)&maxScaleNum,sizeof(int));
......(多条读取语句,及其他语句)
利用CMemFile读取文件是操作内存,应该速度更快一些,结果不是如此,不知什么原因,请高手帮助。谢谢!
http://dev.csdn.net/develop/article/6/6143.shtm
DWORD length = file.GetLength();
BYTE* buffer= new BYTE[length];
file.Read(buffer,length);
memFile.Attach(buffer,length,0);
memFile.SetLength(length);
就是利用CMemFile读取文件时花费了较多的时间。不知原因何在
2.近几天本人也一直在研究内存映射,个人认为读比较小的文件使用内存映射和使用CMemFile是一致的思想。下面的代码摘自《Windows核心编程》第四版第17章内存映射文件的示例,如何使用内存映射对象来对ANSI或Unicode文本文件的内容进行倒序,本人仅摘抄核心代码
BOOL FileReverse(PCTSTR pszPathname, PBOOL pfIsTextUnicode)
{ *pfIsTextUnicode = FALSE; // Assume text is Unicode // Open the file for reading and writing.
HANDLE hFile = CreateFile(pszPathname, GENERIC_WRITE | GENERIC_READ, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE)
{
chMB("File could not be opened.");
return(FALSE);
} // Get the size of the file (I assume the whole file can be mapped).
DWORD dwFileSize = GetFileSize(hFile, NULL);
HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE,
0, dwFileSize + sizeof(WCHAR), NULL); if (hFileMap == NULL)
{
chMB("File map could not be opened.");
CloseHandle(hFile);
return(FALSE);
} // Get the address where the first byte of the file is mapped into memory.
PVOID pvFile = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0); if (pvFile == NULL)
{
chMB("Could not map view of file.");
CloseHandle(hFileMap);
CloseHandle(hFile);
return(FALSE);
}
PSTR pchANSI = (PSTR) pvFile;
// Reverse the contents of the file.
_strrev(pchANSI);
// Clean up everything before exiting.
UnmapViewOfFile(pvFile);
CloseHandle(hFileMap); // Remove trailing zero character added earlier.
SetFilePointer(hFile, dwFileSize, NULL, FILE_BEGIN);
SetEndOfFile(hFile);
CloseHandle(hFile); return(TRUE);
}请高手指点,也谢谢楼上的各位