I wrote two functions to save and read data in a bin file:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// save data in file with name p_file
template <typename T>
void save(string p_file, T data) {
ofstream output(p_file, ios::binary | ios::out);
output.write((char*) &data, sizeof(data));
output.close();
}
// read and return data in file with name p_file
template <typename T>
T read(string p_file) {
ifstream input(p_file, ios::binary | ios::in);
T data;
input.seekg(0, input.end);
int length = input.tellg();
input.seekg(0, input.beg);
input.read((char*) &data, length);
input.close();
return data;
}
int main() {
vector<int> vint;
vint.push_back(1);
save< vector<int> >("test.bin", vint);
vector<int> load_vint = read< vector<int> >("test.bin");
cout << vint[0] << endl;
cout << load_vint[0] << endl;
cout << "done" << endl;
}
expected output:
1
1
done
actual output:
1
1990048
done
Things got even worse when I put most of the code in main into test and didn't change anything in save and read:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// save data in file with name p_file
template <typename T>
void save(string p_file, T data) {
ofstream output(p_file, ios::binary | ios::out);
output.write((char*) &data, sizeof(data));
output.close();
}
// read and return data in file with name p_file
template <typename T>
T read(string p_file) {
ifstream input(p_file, ios::binary | ios::in);
T data;
input.seekg(0, input.end);
int length = input.tellg();
input.seekg(0, input.beg);
input.read((char*) &data, length);
input.close();
return data;
}
// exact same code, just in a function
void testing() {
vector<int> vint;
vint.push_back(1);
save< vector<int> >("test.bin", vint);
vector<int> load_vint = read< vector<int> >("test.bin");
cout << vint[0] << endl;
cout << load_vint[0] << endl;
}
int main() {
testing();
cout << "done" << endl;
}
expected output:
1
1
done
actual output:
1
1924512
What is going on and how do I fix this error?