在C++中拆分文件

Splitting files in C++

本文关键字:文件 拆分 C++      更新时间:2023-10-16

我需要在没有压缩的情况下将一个文件拆分为多个文件。我在cpp参考上找到了这个

#include <fstream>
using namespace std;
int main () {
char * buffer;
long size;
ifstream infile ("test.txt",ifstream::binary);
ofstream outfile ("new.txt",ofstream::binary);
// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
// allocate memory for file content
buffer = new char [size];
// read content of infile
infile.read (buffer,size);
// write to outfile
outfile.write (buffer,size);
// release dynamically-allocated memory
delete[] buffer;
outfile.close();
infile.close();
return 0;
}

我想这样做。但问题是。。我只能创建第一个文件,因为我只能从文件的开头读取数据。可以这样做吗?如果不能。拆分这些文件的最佳方法是什么。

示例代码没有将一个文件拆分为多个文件;它只是复制文件。要将一个文件拆分为多个文件,请不要关闭输入。在伪代码中:

open input
decide size of each block
read first block
while block is not empty (read succeeded):
    open new output file
    write block
    close output file
    read another block

重要的部分是不要关闭输入文件,以便每次读取准确地拾取上一次读取的结束位置。

您可以将流查找到所需位置,然后读取流。检查这段代码。

// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);

你所需要做的就是记住你停止读取内野的位置,关闭外野,打开新外野,重新分配缓冲区,将内野读取到缓冲区,然后写入第二个外野。

您可以从文件中的任何位置读取数据-您已经成功地移动到末尾并返回到开头。

不过,您不需要这样做:只需编写一个循环来顺序读取每个outputSize,并将其写入一个新文件,对于某些outputSize < size

为什么要重新发明轮子-尝试拆分

如果你想在C++中实现它,甚至有源代码可以让你获得想法

我想我已经找到了解决你问题的办法。。。您读取了char数组中的所有第一个文件。然后,将数组的前半部分写入一个文件,然后将数组的后半部分写入另一个文件。。。

例如:

#include <fstream>
using namespace std;
int main () {
char * buffer;
long size;
ifstream infile ("test.txt",ifstream::binary);
ofstream outfile ("new.txt",ofstream::binary);
ofstream outfile2 ("new2.txt",ofstream::binary);
// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
// allocate memory for file content
buffer = new char [size];
// read content of infile
infile.read (buffer,size);
// write to outfile
outfile.write (buffer,size/2);
outfile2.write (buffer+size/2,size);
// release dynamically-allocated memory
delete[] buffer;
outfile.close();
infile.close();
outfile2.close();
return 0;
}

你也可以读前半部分,写出来,然后读后半部分,写下来……看看吧:

int main () {
char * buffer;
long size;
long halfSize;
ifstream infile ("test.txt",ifstream::binary);
ofstream outfile ("new.txt",ofstream::binary);
ofstream outfile2 ("new2.txt",ofstream::binary);
// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
halfSize = static_cast<int>(floor(size/2));
// allocate memory for file content
buffer1 = new char[halfSize];
buffer2 = new char[size-halfSize];
// read content of infile
infile.read (buffer1,halfSize);
infile.read (buffer2,size-halfSize);
// write to outfile
outfile.write (buffer1,halfSize);
outfile2.write (buffer2,size-halfSize);
// release dynamically-allocated memory
delete[] buffer;
delete[] buffer2;
outfile.close();
infile.close();
outfile2.close();
return 0;
}