我希望为一个占用过多内存的程序执行磁盘I/O操作。我使用双精度矩阵,并认为将它们作为字节写入磁盘是最快的方式(我需要保留双精度)。如何实现可移植性?我在这里找到了这段代码(这里),但作者说它不具备可移植性...
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
ofstream ofs( "atest.txt", ios::binary );
if ( ofs ) {
double pi = 3.14;
ofs.write( reinterpret_cast<char*>( &pi ), sizeof pi );
// Close the file to unlock it
ofs.close();
// Use a new object so we don't have to worry
// about error states in the old object
ifstream ifs( "atest.txt", ios::binary );
double read;
if ( ifs ) {
ifs.read( reinterpret_cast<char*>( &read ), sizeof read );
cout << read << '\n';
}
}
return 0;
}
sizeof(double)
在不同平台上可能会有所不同。你需要检查一下,但除此之外,示例代码是可以的。 - spraffdouble
的字节顺序,因为这更有可能改变(特别是如果与任何嵌入式硬件交互)。 - Mark B