ofstream sw(fileName, ios::binary);
if (!sw.is_open()) {
cout << "fail to open " << fileName << endl;
return -1;
sw.write(name.c_str(), 255);
sw.write(reinterpret_cast
(&ni), sizeof(ni));
sw.write(reinterpret_cast(&nj), sizeof(nj));
for (int j = 0; j < nj; j++) {
for (int i = 0; i < ni; i++) {
sw.write(reinterpret_cast(&grid[j][i]), sizeof(grid[j][i]));
sw.close();
return 0;
template
int Model2D::savetxt(string fileName)
ofstream sw(fileName);
if (!sw.is_open()) {
cout << "fail to open " << fileName << endl;
return -1;
sw << "ni=" << ni << " nj=" << nj << endl;
for (int j = 0; j < nj; j++) {
for (int i = 0; i < ni; i++) {
sw << grid[j][i] <<" ";
sw << endl;
sw.close();
return 0;
template
int Model2D::readbin(string fileName)
ifstream fin(fileName, ios::binary);
if (!fin.is_open()) {
cout << "fail to open " << fileName << endl;
return -1;
char s[255];
fin.read(s, 255);
this->name = s;
cout << "name=" << this->name << endl;
int n;
fin.read(reinterpret_cast(&n), sizeof(n));
ni = n;
fin.read(reinterpret_cast(&n), sizeof(n));
nj = n;
cout << "ni=" << ni << " nj =" << nj << endl;
T value;
this->grid = vector>(nj, vector(ni, value));
for (int j = 0; j < nj; j++) {
for (int i = 0; i < ni; i++) {
fin.read(reinterpret_cast(&value), sizeof(value));
grid[j][i] = value;
//cout << value << " ";
//cout << endl;
fin.close();
return 0;
2、测试容器的二进制读写情况
#include <random>
#include <algorithm>
#include "Model2D.h"
using namespace std;
int main()
std::cout << "Hello World!\n";
int ni = 10;
int nj = 5;
//Model2D<float> model2d = Model2D<float>(nj, ni, 1.0, "testName");
auto model2d = Model2D<double>(nj, ni, 1, "testName");
default_random_engine engin(0);
uniform_real_distribution<double> urand(0,1);
//uniform_int_distribution<int> urand(0, 10);
for (int j = 0; j < nj; j++) {
for (int i = 0; i < ni; i++) {
model2d.grid[j][i] = urand(engin);
model2d.savebin("model2d.dat");
model2d.savetxt("model2d.txt");
Model2D<double> model2dr;
model2dr.readbin("model2d.dat");
model2dr.savetxt("model2dr.txt");
return 0;
3、测试结果
ni=10 nj=5
0.592845 0.844266 0.857946 0.847252 0.623564 0.384382 0.297535 0.056713 0.272656 0.477665
0.812169 0.479977 0.392785 0.836079 0.337396 0.648172 0.368242 0.957155 0.140351 0.870087
0.473608 0.800911 0.520477 0.67888 0.720633 0.58202 0.537373 0.758616 0.105908 0.4736
0.186332 0.736918 0.21655 0.135218 0.324141 0.149675 0.222321 0.386489 0.902598 0.44995
0.613063 0.902349 0.0992804 0.969809 0.65314 0.17091 0.358152 0.750686 0.607831 0.325047
ni=10 nj=5
0.592845 0.844266 0.857946 0.847252 0.623564 0.384382 0.297535 0.056713 0.272656 0.477665
0.812169 0.479977 0.392785 0.836079 0.337396 0.648172 0.368242 0.957155 0.140351 0.870087
0.473608 0.800911 0.520477 0.67888 0.720633 0.58202 0.537373 0.758616 0.105908 0.4736
0.186332 0.736918 0.21655 0.135218 0.324141 0.149675 0.222321 0.386489 0.902598 0.44995
0.613063 0.902349 0.0992804 0.969809 0.65314 0.17091 0.358152 0.750686 0.607831 0.325047