Splitting files in C++
Solution 1
You can seek the stream to the desired position and then read stream. Check this piece of code.
// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
All you need to do is to remember the position where you stopped reading infile, close outfile, open new outfile, reallocate buffers and read infile to buffer and write to second outfile.
Solution 2
The example code doesn't split a file into multiple files; it just copies the file. To split a file into multiple files, just don't close the input. In pseudo-code:
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
The important part is not closing the input file, so that each read picks up exactly where the preceding read ended.
Transcendental
Updated on June 04, 2022Comments
-
Transcendental almost 2 years
I need to split a file into multiple files without compression. I found this on cpp reference
#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; }
and I thought to do it like this. But the problem is ..I can create only the 1st file because I can read data only from the beginning of the file. Can it be done like this and if no..what is the best way to split these files.