如何将CFile的内容复制到CMemFile?

时间:2019-04-15 07:00:29

标签: mfc

如何在Windows OS中将CFile的全部内容复制到CMemFile中。 我尝试使用下面的代码复制内容。

CMemFile memFile;
bool b = memFile.Open( L"C:\\test.txt",  CFile::modeReadWrite);
int Length = memFile.GetLength();
unsigned char* buffer = new unsigned char[Length];
memFile.Read((void*)buffer,Length);
memFile.Close();

但是memFile.GetLength返回0。而如果我尝试使用CFile,GetLength()将返回一些有效长度。

CFile f;
bool b1 = f.Open( L"C:\\test.txt",  CFile::modeReadWrite);
int Lengh = f.GetLength();
f.Close();

谢谢。

2 个答案:

答案 0 :(得分:0)

我可以使用下面的代码满足我的要求。

CFile f;
bool b = f.Open( L"C:\\test.txt",  CFile::modeReadWrite);
int nLength = f.GetLength();
BYTE* buffer = new BYTE[nLength];
f.Read((void*)buffer,nLength);
f.Close();
CMemFile memFile;
memFile.Attach(buffer, nLength);

答案 1 :(得分:0)

要将磁盘文件的内容复制到CMemFile实例控制的内存缓冲区中,需要执行以下步骤:

  • 通过正确的选项打开磁盘上的文件。
  • 分配内存以供CMemFile实例使用。
  • 将磁盘内容读取到CMemFile控制的内存缓冲区中。

以下是可能的实现:

// Open file on disk
// typeBinary is necessary to read the raw, untransformed contents
// shareDenyWrite is required to prevent the file from changing in between querying
//     its size and reading the contents
// osSequentialScan could be used to provide an access pattern hint to the OS
//     to allow it to better optimize the (potentially slow) disk accesses
CFile File( L"C:\\test.txt", CFile::modeRead | CFile::typeBinary | CFile::shareDenyWrite );
auto Length = File.GetLength();

// Construct CMemFile instance and allocate memory
CMemFile memFile();
auto buffer = memFile.Alloc( Length );
if ( !buffer ) {
    // Depending on your exception handling system, call AfxThrowMemoryException instead
    throw std::bad_alloc();
}
// Transfer ownership of the buffer to the CMemFile instance
memFile.Attach( buffer, Length );

// Read contents into memory buffer
// Note, that this is limited to file sizes smaller than 4 GB
File.Read( buffer, static_cast<UINT>( Length ) );

到那时,假设在此过程中未引发任何异常,则磁盘文件的全部内容已被读取到CMemFile实例的缓冲区中。所有资源都由C ++对象控制,不需要手动清理。当memFile对象超出范围时,其内存将自动释放。当File实例超出范围时,系统级文件HANDLE将关闭。