Archived

This topic is now archived and is closed to further replies.

Austrian Coder

memory mapped files

Recommended Posts

Austrian Coder    122
Hi! I am tring to do the following: Open a file, map it to memory and print the content to the console. Sounds easy.... Here my try:
m_hFile = CreateFile(Archivname, GENERIC_READ | GENERIC_WRITE, 0, NULL,  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

// could not open file

if (m_hFile == INVALID_HANDLE_VALUE)
{
	return false;
}

	
// create file mapping

m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READWRITE, 0, 0, NULL);

if (m_hMapFile == NULL) 
{
	return false;
}  

// create view of file

m_lpMapAddress = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);

if (m_lpMapAddress == NULL) 
{
	return false;
}

// write the content of the file

cout << (char*)m_lpMapAddress << endl;
HANDLE		m_hMapFile;           // handle for the test file''s memory-mapped region

HANDLE		m_hFile;              // the file handle

LPVOID		m_lpMapAddress;       // pointer to the base address of the memory-mapped region

Whats wrong? Is there a good tutorial out in the net? I have found this one: http://www.flipcode.com/tutorials/tut_filemapping.shtml But i only discuss how to open, map and clode files... Thanks, Christian

Share this post


Link to post
Share on other sites
Kippesoep    892
That should work fine. However, since the file will most likely not have a trailing 0 byte, it won''t know when to stop writing the contents to the screen.

Share this post


Link to post
Share on other sites
Austrian Coder    122
Ok... i have fixed that now, i hope.


m_hFile = CreateFile(Archivname, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

// could not open file

if (m_hFile == INVALID_HANDLE_VALUE)
{
return false;
}

DWORD maxLen = GetFileSize(m_hFile, NULL);

// create file mapping

m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READWRITE, 0, maxLen, NULL);

if (m_hMapFile == NULL)
{
return false;
}

// create view of file

m_lpMapAddress = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);

if (m_lpMapAddress == NULL)
{
return false;
}

cout << (char*)m_lpMapAddress << endl;


And it works... it prints test into the console

[edited by - Austrian Coder on September 4, 2003 6:44:38 AM]

Share this post


Link to post
Share on other sites