Why Read Garbage Value Form File

898 Views Asked by At

I just want to read a file and then update some of its value , But while reading using CFile , It gives garbage value in sFileContent

Here is my Code

CString sWebAppsFile= _T("C:\\newFile.txt");
CString sFileContent;

CFile file;
int len;

if(file.Open(sWebAppsFile, CFile::modeRead))
{
    len = (int) file.GetLength();
    file.Read(sFileContent.GetBuffer(len), len);
    sFileContent.ReleaseBuffer();
    file.Close();
} 

Please provide any solution

1

There are 1 best solutions below

3
Himanshu On

Use this code

CFile file;
CString sWebAppsFile= _T("C:\\newFile.txt");
CString sFileContent;

if(file.Open(sWebAppsFile, CFile::modeRead))
{
    ULONGLONG dwLength = file.GetLength();
    BYTE *buffer = (BYTE *) malloc(dwLength + 1); // Add 1 extra byte for NULL char
    file.Read(buffer, dwLength);  // read character up to dwLength 
    *(buffer + dwLength) = '\0';  // Make last character NULL so that not to get garbage 
    sFileContent = (CString)buffer;        // transfer data to CString (easy to use)
    //AfxMessageBox(sFileContent); 
    free(buffer);                 // free memory
    file.Close();                 // close File
}

Or you can use CStdioFile

CString sWebAppsFile= _T("C:\\newFile.txt");
CStdioFile file (sWebAppsFile, CStdioFile::modeRead); // Open file in read mode
CString buffer, sFileContent(_T(""));

while (file.ReadString(buffer))         //Read File line by line
    sFileContent += buffer +_T("\n");    //Add line to sFileContent with new line character
//AfxMessageBox(sFileContent );
file.Close();                            // close File

Covert BYTE* to CString

BYTE *buffer;
CString sStr((char*)buffer);
// or for unicode:
CString str((const wchar_t*)buffer);