Link to home
Start Free TrialLog in
Avatar of qocarlos
qocarlosFlag for Saint Kitts and Nevis

asked on

Use of CMemFile

Hello:
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

TIA
Avatar of Answers2000
Answers2000

I think you misunderstand CMemFile

Basically the idea of this class is it represents a block of RAM, and then you can use the file operations to access the RAM.

This is handy for the reason you state, or because you can write code that works with memory or disk based files.

Okay now to your specific problem - there isn't a single call (that I know of) to open a disk file and put into a CMemFile object.  What you need to do is :-

1. Open the disk file
2. Read it into memory
3. Close the disk file
4. Construct a CMemFile
5. Use the Attach member of CMemFile to link the memory to the CMemFile object.


Avatar of qocarlos

ASKER

I am not totally sure if I did get your right.
This is what I guess you mean:


//Open the file
CString strFileName = "myfile.txt";
CFile myFile;
CFileException fileException;

if ( !myFile.Open( strFileName , CFile::modeRead ), &fileException )
{
    TRACE( "error");
}
//read the file into memory
BYTE*        pBuffer;
//allocate pBuffer to the maximum size of
//the file
(...)
myFile.Read( pBuffer, sizeof( pBuffer) );

//close the file
//Actually the file will automatically be closed and then //destroyed when it goes out of scope

//Construct a CMemFile an attach attach the block of memory
CMemFile memfile( pBuffer, sizeof(pBuffer));

(...)

If the above code is ok, how could I read now a string?
What I mean is that if I have a file like the following:

abcdefg
efghijk
(...)

how can I process each line?

What I was doing til now was to read each line using fgets, but this approach was too slow since it had to access too many times to the disk (the file could have more than 5000 lines). This is why I thought in reading first everything to the memory.

Any idea?


You can use standard file methods to access data in the CMemFile.
That is Read(), Write(),Seek() and others.
<<to process line
for example:
chDelimeter = '\n'; //<- or any you wish
char szBufer[SZ_MAX_LINE_LENGTH] = "";
BYTE symbol = ;
DWORD dwCount = 0;
int nPos;
while (dwCount < memfile.GetLength())
{
nPos = 0;
do{
dwCount+= memfile.Read(&symbol, 1);
szBufer[nPos++] = symbol;
}while (symbol != chDelimeter);
szBuffer[nPos-=2] = '\0'; //<- remove delimeter
// here you got in the szBuffer entire line.
};
ASKER CERTIFIED SOLUTION
Avatar of Answers2000
Answers2000

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks a lot.
Now I know how to continue importing and processing my files