一、内存到内存
在C++中,内存copy操作通常使用std::copy
函数,它在<algorithm>
头文件中定义。std::copy
可以将一个范围内的元素复制到另一个范围。
补充说明:C++ 内存管理库 <memory> | 菜鸟教程 (runoob.com)
以下是使用std::copy
的一个简单例子:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
// 初始化源数组
int sourceArray[] = {1, 2, 3, 4, 5};
int sourceArraySize = sizeof(sourceArray) / sizeof(sourceArray[0]);
// 初始化目标数组
int targetArray[5];
std::vector<int> targetVector(5);
// 使用std::copy将sourceArray复制到targetArray
std::copy(sourceArray, sourceArray + sourceArraySize, targetArray);
// 使用std::copy将sourceArray复制到targetVector
std::copy(sourceArray, sourceArray + sourceArraySize, targetVector.begin());
// 打印结果以验证复制成功
for (int i = 0; i < sourceArraySize; ++i) {
std::cout << "targetArray[" << i << "] = " << targetArray[i] << std::endl;
}
for (size_t i = 0; i < targetVector.size(); ++i) {
std::cout << "targetVector[" << i << "] = " << targetVector[i] << std::endl;
}
return 0;
}
二、 文件到内存buf
C++ 文件输入输出库 – <fstream> | 菜鸟教程 (runoob.com)
#include <iostream>
#include <fstream>
int fileReadBuf()
{
std::filebuf *pbuf;
std::ifstream filestr;
long size;
char * buffer;
// 要读入整个文件,必须采用二进制打开
filestr.open ("../TestCase-1.txt", std::ios::binary);
if (!filestr) {
std::cerr << "Unable to open file!" << std::endl;
return -1; // 文件打开失败
}
// 获取filestr对应buffer对象的指针
pbuf=filestr.rdbuf();
// 调用buffer对象方法获取文件大小
size=pbuf->pubseekoff (0,std::ios::end,std::ios::in);
std::cerr << "File size is " << size << std::endl;
pbuf->pubseekpos (0,std::ios::in);
// 分配内存空间
buffer = new char[size];
// 获取文件内容
pbuf->sgetn (buffer,size);
filestr.close();
// 输出到标准输出
std::cout.write (buffer,size);
// 释放内存空间
delete[] buffer;
return 1;
}