首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将CFile的内容复制到CMemFile?

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

Stack Overflow用户
提问于 2019-04-15 15:00:29
回答 2查看 432关注 0票数 1

如何在windows操作系统中将CFile的全部内容复制到CMemFile中。我尝试了下面的代码来复制内容。

代码语言:javascript
复制
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()会返回一些有效的长度。

代码语言:javascript
复制
CFile f;
bool b1 = f.Open( L"C:\\test.txt",  CFile::modeReadWrite);
int Lengh = f.GetLength();
f.Close();

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2019-04-15 21:17:25

我能够实现我的要求使用以下代码。

代码语言:javascript
复制
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);
票数 0
EN

Stack Overflow用户

发布于 2019-04-16 17:01:12

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

  • 打开磁盘上的文件,传递正确的options.
  • Allocate内存供CMemFile实例使用。
  • 将磁盘内容读取到CMemFile-controlled内存缓冲区。

以下是一种可能的实现:

代码语言:javascript
复制
// 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将关闭。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55683963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档