从CFile阅读CByteArray

时间:2013-11-29 23:54:10

标签: c++ file-io mfc cfile

我正在将CByteArray写入档案:

    CFile myFile;
CByteArray m_baToques;

    if(myFile.Open(_T(file), CFile::modeReadWrite | CFile::modeCreate))
    {
        myFile.Write(m_baToques.GetData(),m_baToques.GetSize());
        myFile.Write(m_baDst.GetData(), m_baDst.GetSize());
        myFile.Write(m_baFeriados.GetData(), m_baFeriados.GetSize());
    }

现在如何从文件中读取CByteArray?

我试试:

    CFile myFile;    
    if(myFile.Open(_T(file), CFile::modeReadWrite | CFile::modeCreate))
    {
        myFile.Read(m_baToques,m_baToques.GetSize());
        myFile.Read(m_baDst, m_baDst.GetSize());
        myFile.Read(m_baFeriados, m_baFeriados.GetSize());
    }
  

错误C2664:'CFile :: Read':无法将参数1从'CByteArray'转换为'void *'

2 个答案:

答案 0 :(得分:0)

查看documentation for CFile::Read,我们发现它需要两个参数:

  

virtual UINT CFile::Read(void* lpBuf, UINT nCount);

     

lpBuf

     

指向用户提供的缓冲区的指针,该缓冲区用于接收从文件读取的数据。

     

NCOUNT

     

从文件中读取的最大字节数。对于文本模式文件,回车换行对被计为单个字符。

lpBuf 不属于CByteArray类型。它是void*。因此编译错误。

要阅读CByteArray,我们需要allocate a buffer via CByteArrayget a pointer to said buffer我们可以用于 lpBuf

CByteArray buffer;
buffer.SetSize(1024); // ensure that buffer is allocated and the size we want it
UINT bytesRead = myFile.Read(buffer.GetData(), buffer.GetSize());
// use bytesRead value and data now in buffer as needed

请注意,在您的问题中,您在阅读路径上有以下行:

  

if(myFile.Open(_T(file), CFile::modeReadWrite | CFile::modeCreate))

CFile::modeCreate将导致文件被截断为0字节。没有什么可读的。

你的意思是写更像这样的东西吗?

if(myFile.Open(_T(file), CFile::modeRead | CFile::typeBinary | CFile::modeNoTruncate))

答案 1 :(得分:0)

用完整的功能代码完成问题: (在Visual Studio 2017下测试)

BOOL ReadBinaryFile(TCHAR * filename){

CFileStatus filestatus;
BOOL ok = CFile::GetStatus(filename, filestatus);
if (!ok)
    return FALSE;

CFile myFile;
ok = myFile.Open(filename, CFile::modeRead | CFile::typeBinary | CFile::modeNoTruncate);
if (!ok)
    return FALSE;

INT_PTR SIZE = (INT_PTR) filestatus.m_size;

// To read into a CByteArray, we need to allocate a buffer via CByteArray and get a pointer to said buffer that we can use for lpBuf:
CByteArray buffer;
buffer.SetSize(SIZE); // ensure that buffer is allocated and the size we want it
UINT bytesRead = myFile.Read(buffer.GetData(), SIZE);

myFile.Close();
return TRUE;

}