如何在windows操作系统中将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();谢谢。
发布于 2019-04-15 21:17:25
我能够实现我的要求使用以下代码。
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);发布于 2019-04-16 17:01:12
要将磁盘文件的内容复制到CMemFile实例控制的内存缓冲区中,需要执行以下步骤:
CMemFile实例使用。CMemFile-controlled内存缓冲区。以下是一种可能的实现:
// 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将关闭。
https://stackoverflow.com/questions/55683963
复制相似问题