Problem : Use of CMemFile

Problem : Use of CMemFile

I want to use the class CMemFile in order to read a entire file into memory and then then work with it in place in memory but I don’t know how to work with it.
I don’t see how to open a file (for instance “c:\myfile.txt”) using the CMemFile constructor.
Any help, source code would be very apreciated

 

Solution : Use of CMemFile 

In your code, This line
CMemFile memfile( pBuffer, sizeof(pBuffer));

attaches the CMemFile to the memory you just read in (this version of the CMemFile construction includes an implicit Attach – step #5 of my first answer – see the VC help if you don’t believe me)

Then you just use the Read member of CMemFile to get the data out of the file byte-by-byte.

CMemFile includes over-ridden versions of the Seek and Read members of CFile (i.e. they do the same job).

Incidentally you can read the source for CMemFile in FILEMEM.CPP in the MFC Source directory (if you want to know how it works), or the code around line 1300 (VC5, might be diff on VC6) of AFX.H

This is the class definition of CMemFile

class CMemFile : public CFile
{
DECLARE_DYNAMIC(CMemFile)

public:
// Constructors
CMemFile(UINT nGrowBytes = 1024);
CMemFile(BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0);

// Operations
void Attach(BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0);
BYTE* Detach();

// Advanced Overridables
protected:
virtual BYTE* Alloc(DWORD nBytes);
virtual BYTE* Realloc(BYTE* lpMem, DWORD nBytes);
virtual BYTE* Memcpy(BYTE* lpMemTarget, const BYTE* lpMemSource, UINT nBytes);
virtual void Free(BYTE* lpMem);
virtual void GrowFile(DWORD dwNewLen);

// Implementation
protected:
UINT m_nGrowBytes;
DWORD m_nPosition;
DWORD m_nBufferSize;
DWORD m_nFileSize;
BYTE* m_lpBuffer;
BOOL m_bAutoDelete;

public:
virtual ~CMemFile();
#ifdef _DEBUG
virtual void Dump(CDumpContext& dc) const;
virtual void AssertValid() const;
#endif
virtual DWORD GetPosition() const;
BOOL GetStatus(CFileStatus& rStatus) const;
virtual LONG Seek(LONG lOff, UINT nFrom);
virtual void SetLength(DWORD dwNewLen);
virtual UINT Read(void* lpBuf, UINT nCount);
virtual void Write(const void* lpBuf, UINT nCount);
virtual void Abort();
virtual void Flush();
virtual void Close();
virtual UINT GetBufferPtr(UINT nCommand, UINT nCount = 0,
void** ppBufStart = NULL, void** ppBufMax = NULL);

// Unsupported APIs
virtual CFile* Duplicate() const;
virtual void LockRange(DWORD dwPos, DWORD dwCount);
virtual void UnlockRange(DWORD dwPos, DWORD dwCount);
};

You can see it overrides most functions in CFile.  You should be aware some of the functions (that don’t magic logical sense on a block of memory) simply throw an exception and do nothing else, but the basics (Read, Write, Seek) are all there.

Having said all this the other alternative to construction the CMemFile is to just use pBuffer as a normal block of memory, and step thru it using normal pointer type stuff.