我想爲需要太多RAM的程序執行磁盤I/O操作。 我使用雙打矩陣,並認爲寫入磁盤的字節是最快的方式(我需要保持雙精度)。C++從二進制文件中寫入和讀取雙精度
如何做到攜帶方便?
我發現這個代碼(here),但筆者認爲這不是便攜式...
#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(雙)'可能是跨平臺的不同。你需要檢查這個,否則示例代碼是可以的。 – spraff
我更擔心'double'的字節順序,因爲它更有可能改變(特別是與任何嵌入式硬件交互時)。 –
的確,儘管用「可能」來談論和思考是一種壞習慣。如果你真的關心可移植性,那麼它沒有程度。 – spraff