1: //binary_file1.cpp
3: #include <iostream>
4: #include <fstream>
5: using namespace std;
7: int main()
8: {
9: cout << "\nThis program reads in a single integer, then writes "
10: "that integer out to both\na textfile and a binary file, thus "
11: "allowing the user to easily compare the two\noutputs. The two "
12: "files should be compared for both size and content. Try the "
13: "\nvalues 3, 7, 1234 and 1234567, for example.";
14: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
16: int i;
17: cout << "\nEnter your integer value here: ";
18: cin >> i; cin.ignore(80, '\n');
20: ofstream outFileText("binary_file1.txt");
21: fstream outFileBinary("binary_file1.bin",
22: ios::trunc | ios::out | ios::binary);
24: ////An alternative to the above two lines is:
25: //ofstream outFileText;
26: //outFileText.open("binary_file1.txt");
27: //fstream outFileBinary;
28: //outFileBinary.open("binary_file1.bin",
29: // ios::trunc | ios::out | ios::binary);
31: outFileText << i;
32: outFileBinary.write((char *)&i, sizeof(i));
34: outFileText.close();
35: outFileBinary.close();
36: cout << "\nThe integer " << i << " has now been written to both "
37: "files.\nCheck the size and content of binary_file1.txt and "
38: "binary_file1.bin.";
39: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
40: }