binary reading and writing to file

Hi, im having problem again
I have this exercise where i have to split program that inside book into 2 parts

1. reading from file in binary stream mode
2. writing to another file int binary stream mode
3. check if they are the same

I did split that program in book in 2 parts but i had different results
original file content was
This is my text

but i got as output
This is my t


So i decided to check out how the code inside book would work without changing it at all. I got exactly the same results.

We haven't yet covered all the template stuff but he gave the code for it too.

Can anyone tell me why im getting these wrong results?

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
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Bad{};

template<class T>
char* as_bytes(T&i){
	void* addr = &i;
	return static_cast<char*>(addr);
}

int main()
{

	//input file name
	cout << "Please enter input file name\n ";
	string iname;
	cin >> iname;
	ifstream ifs(iname, ios_base::binary);
	if (!ifs) throw Bad{};

	//output file name
	cout << " Please enter output file name\n";
	string oname;
	cin >> oname;
	ofstream ofs(oname, ios_base::binary); 
	if (!ofs) throw Bad{};

	//reading
	vector<int> v;
	for (int x; ifs.read(as_bytes(x), sizeof(int));)
		v.push_back(x);


	for (int x : v) cout << x << endl; // looking at number i got
        //my own improvement of the code

	//writing what read to other file
	for (int x : v)
		ofs.write(as_bytes(x), sizeof(int)); // note : writing bytes

	ofs.close(); // this i added also because without closing the file i got 
        //an empty file after program finished running

	system("pause");
	return 0;
}
Topic archived. No new replies allowed.