大文件的分段拷贝以及拼接
需要头文件fstream、iomanip支持以及自定义宏
#define ONE_FILE_SIZE (1024 * 1024 * 10) // 单个文件的最大容量
#define EACH_BLOCK (1024 * 8) // 一次读取的字节数
typedef long long ll;
文件的分段拷贝
void moreFileCopy(const string& fileName)
{
string copyFileName = fileName;
ifstream ifs(fileName, ios::binary);
if (ifs.is_open()) {
ifs.seekg(0, ios::end);
ll fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
char buffer[EACH_BLOCK] = { 0 };
int i = 0;
string fileName = copyFileName;
for (int i = 0; !ifs.eof(); ++i) {
string fileName1 = fileName;
ofstream ofs(fileName1.insert(fileName.rfind('.'), to_string(i)), ios::binary);
while (!ifs.eof() && ofs.tellp() < ONE_FILE_SIZE) {
ifs.read(buffer, sizeof(buffer));
ll len = ifs.gcount();
ofs.write(buffer, len);
ofs.flush();
ll curSize = ONE_FILE_SIZE * i + ofs.tellp();
cout << "文件编号[" << i << "]=>" \
<< fixed << setprecision(2) << "文件总大小: " << ((double)fileSize / 1024 / 1024) \
<< "MB;当前大小: " << ((double)curSize / 1024 / 1024) << "MB;当前进度: " \
<< ((double)curSize / fileSize) * 100 << "%" << endl;
}
ofs.close();
}
ifs.close();
}
}
效果展示
分段拼接
分段拼接的文件名为去掉0,1,2标号后的文件名。
void moreFileCat(const string& fileName)
{
ofstream ofs(fileName, ios::binary);
char buffer[EACH_BLOCK] = { 0 };
for (int i = 0; true; ++i) {
string fileName1 = fileName;
ifstream ifs(fileName1.insert(fileName.rfind('.'), to_string(i)), ios::binary);
if (!ifs.is_open()) {
break;
}
ifs.seekg(0, ios::end);
ll fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
while (!ifs.eof()) {
ifs.read(buffer, sizeof(buffer));
ll len = ifs.gcount();
ofs.write(buffer, len);
ofs.flush();
ll curSize = ofs.tellp() - (ll)(ONE_FILE_SIZE * i);
cout << "文件编号[" << i << "]=>" \
<< fixed << setprecision(2) << "文件总大小: " << ((double)fileSize / 1024 / 1024) \
<< "MB;当前大小: " << ((double)curSize / 1024 / 1024) << "MB;当前进度: " \
<< ((double)curSize / fileSize) * 100 << "%" << endl;
}
ifs.close();
}
ofs.close();
}