gpt4 book ai didi

c++ - 在 C++ 中分割一个大文件

转载 作者:可可西里 更新时间:2023-11-01 17:57:19 27 4
gpt4 key购买 nike

我正在尝试编写一个程序,将一个大文件(任何类型)拆分成许多较小的“ block ”。我想我已经掌握了基本的想法,但出于某种原因我无法创建超过 12 kb 的 block 大小。我知道在谷歌等网站上有一些解决方案,但我更感兴趣的是了解这个限制的起源是什么,然后实际使用该程序来分割文件。

//This file splits are larger into smaller files of a user inputted size.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include <direct.h>
#include <stdlib.h>
using namespace std;

void GetCurrentPath(char* buffer)
{
_getcwd(buffer, _MAX_PATH);
}


int main()
{
// use the function to get the path
char CurrentPath[_MAX_PATH];
GetCurrentPath(CurrentPath);//Get the current directory (used for displaying output)

fstream bigFile;
string filename;
int partsize;
cout << "Enter a file name: ";
cin >> filename; //Recieve target file
cout << "Enter the number of bites in each smaller file: ";
cin >> partsize; //Recieve volume size

bigFile.open(filename.c_str(),ios::in | ios::binary);
bigFile.seekg(0, ios::end); // position get-ptr 0 bytes from end
int size = bigFile.tellg(); // get-ptr position is now same as file size
bigFile.seekg(0, ios::beg); // position get-ptr 0 bytes from beginning

for (int i = 0; i <= (size / partsize); i++)
{
//Build File Name
string partname = filename; //The original filename
string charnum; //archive number
stringstream out; //stringstream object out, used to build the archive name
out << "." << i;
charnum = out.str();
partname.append(charnum); //put the part name together

//Write new file part
fstream filePart;
filePart.open(partname.c_str(),ios::out | ios::binary); //Open new file with the name built above
//Check if near the end of file
if (bigFile.tellg() < (size - (size%partsize)))
{
filePart.write(reinterpret_cast<char *>(&bigFile),partsize); //Write the selected amount to the file
filePart.close(); //close file
bigFile.seekg(partsize, ios::cur); //move pointer to next position to be written
}
//Changes the size of the last volume because it is the end of the file
else
{
filePart.write(reinterpret_cast<char *>(&bigFile),(size%partsize)); //Write the selected amount to the file
filePart.close(); //close file
}
cout << "File " << CurrentPath << partname << " produced" << endl; //display the progress of the split
}


bigFile.close();
cout << "Split Complete." << endl;
return 0;
}

有什么想法吗?

最佳答案

您正在写入拆分文件,而不是从大文件中读取。你写的是大文件的内存结构,而不是大文件的内容。您需要分配一个缓冲区,从大文件中读取它并将其写入拆分文件。

关于c++ - 在 C++ 中分割一个大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541433/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com