只是为了好玩,我编写了这些通用助手来将任意二维数组写入二进制流:
namespace arraystream
{
template <class T, size_t M> std::istream& operator>>(std::istream& is, const T (&t)[M])
{ return is.read ((char*) t, M*sizeof(T)); }
template <class T, size_t M> std::ostream& operator<<(std::ostream& os, const T (&t)[M])
{ return os.write((char*) t, M*sizeof(T)); }
template <class T, size_t N, size_t M> std::istream& operator>>(std::istream& is, const T (&tt)[N][M])
{ for (size_t i=0; i<N; i++) is >> tt[i]; return is; }
template <class T, size_t N, size_t M> std::ostream& operator<<(std::ostream& os, const T (&tt)[N][M])
{ for (size_t i=0; i<N; i++) os << tt[i]; return os; }
}
您可以在代码中像这样使用它们:
char c [23] [5];
float f [7] [100];
uint16_t r2[100][100]; // yes that too
std::ofstream ofs("output.raw", std::ios::binary || std::ios::out);
ofs << c << f << r2;
ofs.flush();
ofs.close();
////
std::ifstream ifs("output.raw", std::ios::binary || std::ios::in);
ifs >> c >> f >> r2;
ifs.close();
这里唯一的小缺点是,如果您要在命名空间 std 中声明这些(或一直是 use 它们),编译器也会尝试使用这些重载来编写 std::cout << "hello world"(即 @987654325 @ 在那里)。我在需要时选择明确地use arraystream 命名空间,请参阅下面的完整示例。
这是一个完整的可编译示例,通过校验和哈希显示读回的数据确实相同。 不需要 Boost 来使用这些助手。我使用 boost::random 来获取一组随机数据, boost::hash 来做校验和。您可以使用任何随机生成器,也可以使用外部校验和工具。
事不宜迟:
#include <fstream>
#include <boost/random.hpp>
#include <boost/functional/hash.hpp>
namespace arraystream
{
template <class T, size_t M> std::istream& operator>>(std::istream& is, const T (&t)[M]) { return is.read ((char*) t, M*sizeof(T)); }
template <class T, size_t M> std::ostream& operator<<(std::ostream& os, const T (&t)[M]) { return os.write((char*) t, M*sizeof(T)); }
template <class T, size_t N, size_t M> std::istream& operator>>(std::istream& is, const T (&tt)[N][M])
{ for (size_t i=0; i<N; i++) is >> tt[i]; return is; }
template <class T, size_t N, size_t M> std::ostream& operator<<(std::ostream& os, const T (&tt)[N][M])
{ for (size_t i=0; i<N; i++) os << tt[i]; return os; }
}
template <class T, size_t N, size_t M>
size_t hash(const T (&aa)[N][M])
{
size_t seed = 0;
for (size_t i=0; i<N; i++)
boost::hash_combine(seed, boost::hash_range(aa[i], aa[i]+M));
return seed;
}
int main()
{
uint16_t data[100][100];
{
// make some (deterministic noise)
boost::mt19937 rand(0);
for (int i=0; i<100; i++) for (int j=0; j<100; j++) data[i][j] = rand();
}
{
// write a file
std::ofstream ofs;
ofs.open("output.raw", std::ios::out | std::ios::binary);
using namespace arraystream;
ofs << data;
ofs.flush();
ofs.close();
}
uint16_t clone[100][100];
{
// read a file
std::ifstream ifs;
ifs.open("output.raw", std::ios::in | std::ios::binary);
using namespace arraystream;
ifs >> clone;
ifs.close();
}
std::cout << "data: " << hash(data) << std::endl;
std::cout << "clone: " << hash(clone) << std::endl;
return 0;
}