forked from borisbrodski/sevenzipjbinding
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmysplit.cpp
74 lines (60 loc) · 1.7 KB
/
mysplit.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>
#define BLOCK_SIZE (1024 * 128)
using namespace std;
int main(int argc, char *argv[]) {
if (argc != 4) {
cout << "Usage:" << endl;
cout << " mysplit <file> <chunk size in bytes> <chunk prefix>" << endl;
return 1;
}
string input_filename(argv[1]);
string prefix(argv[3]);
istringstream chunk_size_stream(argv[2]);
streamsize chunk_size;
chunk_size_stream >> chunk_size;
if (chunk_size_stream.fail() || !chunk_size_stream.eof()) {
cerr << "ERROR: Invalid chunk size '" << argv[2] << "'" << endl;
return 1;
}
ifstream input(input_filename.c_str(), ios::binary);
if (input.fail()) {
cerr << "Error opening file for reading: " << input_filename << endl;
return 1;
}
char * buffer = new char [BLOCK_SIZE];
for (int chunk_number = 1; input.good() ; chunk_number++) {
ostringstream chunk_filename;
chunk_filename << prefix << setw(5) << setfill('0') << chunk_number;
ofstream chunk(chunk_filename.str().c_str(), ios::binary);
if (chunk.fail()) {
input.close();
delete[] buffer;
cerr << "Error opening file for writing: " << chunk_filename.str() << endl;
return 1;
}
int to_read = chunk_size;
while (input.good() && to_read > 0) {
int try_to_read = to_read > BLOCK_SIZE ? BLOCK_SIZE : to_read;
input.read(buffer, try_to_read);
streamsize read = input.gcount();
if (read > 0) {
to_read -= read;
if (!chunk.write(buffer, read)) {
input.close();
chunk.close();
delete[] buffer;
cerr << "Error writing into the file: " << chunk_filename.str() << endl;
return 1;
}
}
}
chunk.close();
}
delete[] buffer;
input.close();
return 0;
}