Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am reading the contents of a file into a bufer ready to populate a window in an MFC app.

My code is:
    //read file
CFile* pFile = new CFile(filePathAndName, CFile::modeRead);
ULONGLONG dwLength = pFile->GetLength();//I64u
char* buffer = new char[(int)dwLength];
UINT nActual = pFile->Read(buffer, dwLength);//sizeof(szBuffer));


However, I lways get about 10-12 characters of garbage right at the end of the buffer - it usually looks something like:
ýýýý««««««««îþîþ

Can anyone tell me where this comes from and how to remove it please. I even get it if the file is empty.
Posted
Comments
CPallini 25-Oct-11 5:13am    
Did you check 'nActual' value?
Jackie Lloyd 25-Oct-11 5:54am    
nActual has the same value as dwLength - is this as it should be? Should I insert an eof character after the character with position nActual?

Dave's answer is absolutely correct, however a better solution to the problem would be
C++
//read file
CFile* pFile = new CFile(filePathAndName, CFile::modeRead);
ULONGLONG dwLength = pFile->GetLength();//I64u
char* buffer = new char[(int)dwLength + 1]; //Notice the +1
buffer[dwLength] = 0; //This will make the last character a null terminator
UINT nActual = pFile->Read(buffer, dwLength);//sizeof(szBuffer));


This will allow you to use the file contents with any C++ function as a normal string
 
Share this answer
 
Comments
Jackie Lloyd 25-Oct-11 9:44am    
many thanks - makes perfect sense when you see it!
There is no null terminating character when reading like this - so you are adding the end of the buffer - what's the line when you set your string? You need to make sure you use nActual characters only - otherwise you'll get garbage at the end :)
 
Share this answer
 
Comments
Jackie Lloyd 25-Oct-11 5:54am    
nActual has the same value as dwLength - is this as it should be? Should I insert an eof character or null character \0 after the character with position nActual?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900