Howto Read From Binary File
Dear all,
The following code first writes the data
into a binary file. Then reading the file again.
However the output it gives after
reading it is faulty.
How can I correct it?
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
|
#include <iostream>
#include <fstream>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
template <class T> T prn_vec(vector<T>& arg) {
for ( int n=0; n<arg.size() ; n++ ) {
cout << arg[n] << " ";
}
cout << endl;
}
int main()
{
vector <char> digit;
vector <vector <char> > Repo;
digit.push_back('0');
digit.push_back('0');
digit.push_back('1');
Repo.push_back(digit);
digit.clear();
digit.push_back('1');
digit.push_back('0');
digit.push_back('1');
Repo.push_back(digit);
digit.clear();
// Process vector within Repo
// Write them as binary file
ofstream out("test.bin", ios::out | ios::binary | ios::app);
if(!out) {
cout << "Cannot open file.\n";
return 1;
}
for ( int i=0; i<Repo.size() ; i++ ) {
char *array = new char[Repo[i].size()];
prn_vec<char>(Repo[i]);
out.write((char *) &array, sizeof array);
delete[] array;
}
out.close();
ifstream in("test.bin", ios::in | ios::binary);
if(!in) {
cout << "Cannot open file.\n";
return 1;
}
// Reading it
cout << endl;
cout << "READING FROM BINARY FILE AND PRINT" << endl;
char n[3];
in.read((char *) &n, sizeof n);
for(int i = 0; i <4; i++) {
cout << n[i] << " ";
}
in.close();
cout << endl;
unlink("test.bin");
return 0;
}
|
Last edited on
Topic archived. No new replies allowed.