天天看點

C++ 跨平台開發的坑集合C++ 跨平台開發的坑集合

C++ 跨平台開發的坑集合

std::fstream引發的血案

std::fstream::open函數:

void open (const char* filename,
           ios_base::openmode mode = ios_base::in | ios_base::out);
void open (const string& filename,
           ios_base::openmode mode = ios_base::in | ios_base::out);
           

案發現場:

std::fstream file;
char buf[10] = {0,1,2,3,4,5,6,7,8,9};
file.open("test.dat",ios::truncate|ios::out);
file.write(buf,10);
file.close();
           

Linux平台檔案大小是10個位元組,winzhedows平台檔案大小 > 10個位元組

納尼。。。什麼鬼。。。

百般折騰,頭發抓掉一把一把,折騰了大半天後,終于靈光一閃,是不是少了個标志,加上

ios::binary

後果然神力顯現,經過驗證大小都一樣了。

解鎖正确姿勢如下:

std::fstream file;
char buf[10] = {0,1,2,3,4,5,6,7,8,9};
file.open("test.dat",ios::truncate|ios::out|ios::binary);
file.write(buf,10);
file.close();
           

持續更新中。。。

繼續閱讀