main.cpp
1 #include <iostream> 2 #include <fstream> 3 #include <stdlib.h> 4 #include <string> 5 #include <windows.h> 6 7 using namespace std; 8 9 int main ( int argc, char* argv[] ) { 10 if ( argc != 4 && argc != 5 ) { 11 cout << "File Split 1.0" << endl; 12 cout << " Usage: fs <source file> <off begin> <off end> [<destination file>]" << endl; 13 cout << " e.g. fs app.exe 0 127 0_127.dat" << endl; 14 cout << " e.g. fs app.exe 0 127" << endl; 15 return -1; 16 } 17 fstream src ( argv[1], ios::in | ios::binary | ios::ate ); 18 if ( src.is_open() ) { 19 long long srcSize = static_cast<long long> ( src.tellg() ); 20 cout << "<source file> size: " << srcSize << " bytes" << "." << endl; 21 long lgBegin = strtol ( argv[2], NULL, 10 ); 22 long lgEnd = strtol ( argv[3], NULL, 10 ); 23 std::ios_base::seekdir offBegin = static_cast<std::ios_base::seekdir> ( lgBegin ); 24 std::ios_base::seekdir offEnd = static_cast<std::ios_base::seekdir> ( lgEnd ); 25 if ( offBegin >= 0 && offEnd < srcSize && offBegin <= offEnd ) { 26 string dstPath = ""; 27 if ( argc == 5 ) { 28 dstPath += argv[4]; 29 } else { 30 char buf[32]; 31 dstPath += ltoa ( lgBegin, buf, 10 ); 32 dstPath += "_"; 33 dstPath += ltoa ( lgEnd, buf, 10 ); 34 dstPath += ".bin"; 35 } 36 cout << "Offsets with " << offBegin << " ~ " << offEnd << "." << endl; 37 fstream dst ( dstPath.c_str(), ios::out | ios::binary | ios::trunc ); 38 if ( dst.is_open() ) { 39 src.seekg ( offBegin ); 40 for ( int i = offBegin; i <= offEnd; i++ ) { 41 dst.put ( src.get() ); 42 } 43 dst.flush(); 44 dst.close(); 45 src.close(); 46 cout << "<destination file> expected size: " << offEnd - offBegin + 1 << " bytes" << "." << endl; 47 fstream chk ( dstPath.c_str(), ios::in | ios::binary | ios::ate ); 48 if ( chk.is_open() ) { 49 long long chkSize = static_cast<long long> ( chk.tellg() ); 50 chk.close(); 51 cout << "<destination file> actual size: " << chkSize << " bytes" << "." << endl; 52 cout << "<destination file> state " << ( chkSize != offEnd - offBegin + 1 ? "bad" : "good" ) << "." << endl; 53 } else { 54 cout << "Can not open <destination file> file." << endl; 55 return -1; 56 } 57 cout << "File split completed." << endl; 58 return 0; 59 } else { 60 src.close(); 61 cout << "Can not create <destination file> file." << endl; 62 return -1; 63 } 64 } else { 65 src.close(); 66 cout << "Invalid offsets. The allowed offsets is 0 ~ " << srcSize - 1 << "." << endl; 67 return -1; 68 } 69 } else { 70 cout << "Can not open <source file> file." << endl; 71 return -1; 72 } 73 }
附件1