-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryCopy++.cpp
More file actions
94 lines (88 loc) · 2.83 KB
/
binaryCopy++.cpp
File metadata and controls
94 lines (88 loc) · 2.83 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Purpose: binary file I/O example
* Author: Emanuele Rizzolo
* Class: 3XIN
* Date: 2020/04/26
* Note:
*/
// directive for standard io functions
#include <iostream>
// directive for file io functions
#include <fstream>
using namespace std;
// should be optimized according to filesystem
#define BUFFER_SIZE 1024 // 1 KB
#define DEBUG 1
// main function
int main(int argc, char *argv[])
{
if (argc == 3)
{
// open the file for input
// automatic open with explicit open mode in and binary
ifstream infile(argv[1], ios::in | ios::binary);
// check failure
if (infile)
{
// success
// open the file for output
// automatic open with explicit open mode out and binary
ofstream outfile(argv[2], ios::out | ios::binary);
// check failure
if (outfile)
{
// success
// allocate buffer
char *buffer = new char[BUFFER_SIZE];
if (buffer == nullptr)
{
cout << "Cannot allocate buffer memory for " << BUFFER_SIZE << " bytes" << endl;
}
else
{
// I/O operations
size_t letti, scritti, lastPos = outfile.tellp();
do
{
infile.read(buffer, BUFFER_SIZE);
letti = infile.gcount();
if (letti > 0)
{
if (DEBUG)
{
cout << letti << " bytes read" << endl;
}
outfile.write(buffer, letti);
scritti = outfile.tellp() - lastPos;
lastPos = outfile.tellp();
if (scritti != letti)
{
cerr << "Written " << scritti << " bytes instead of " << letti << endl;
}
}
} while (letti > 0);
// free allocated memory
delete[] buffer;
}
// close file
outfile.close();
}
else
{
cout << "failed to open file " << argv[2] << endl;
}
// close file
infile.close();
}
else
{
cout << "failed to open file " << argv[1] << endl;
}
}
else
{
cout << "Usage " << argv[0] << " <inputfile> <outputfile>" << endl;
}
// successful termination
return 0;
}