-1

我只想读取一个文件,然后更新它的一些值,但是在使用 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();
} 

请提供任何解决方案

4

1 回答 1

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);
于 2016-01-08T09:53:44.957 回答