为什么要阅读垃圾值表单文件

时间:2016-01-08 06:39:10

标签: c++ visual-c++ mfc cfile

我只是想读取一个文件,然后更新它的一些值, 但是在使用CFile阅读时,它会在 sFileContent

中提供垃圾值

这是我的代码

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();
} 

请提供任何解决方案

1 个答案:

答案 0 :(得分:0)

使用此代码

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
}

或者您可以使用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

将BYTE *隐藏到CString

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