我需要在程序中处理二进制文件,我已经看到使用了 reinterpret_cast 以及 c_str()。
这是使用 c_str() 的代码片段:
fstream aFile;
string sample = "hello this is a line of code";
aFile.open("newFile.bin", ios::out | ios::binary);
aFile.write(sample.c_str(), sample.size());
aFile.close();
这是使用 reinterpret_cast 的代码片段:
fstream aFile_2;
string sample_2 = "hello this is a line of code";
aFile_2.open("newFile_2.bin", ios::out | ios::binary);
aFile_2.write(reinterpret_cast<char *>(&sample_2), sizeof(sample_2));
aFile_2.close();
当我写入使用 reinterpret_cast 的二进制文件时,我得到了乱码......当我将数据读回我的程序时,这是有道理的。但是,当我使用 c_str() 时,数据在我写入的文件中是有意义的(没有乱码)。
而且,在使用 c_str() 写入文件后,我可以使用 getline 或 >> 轻松检索数据:
string result = "";
aFile.open("newFile.bin", ios::in | ios::binary);
//aFile >> result;
getline(aFile, result);
cout << "result = " << result << endl;
aFile.close();
所以,我的问题是,哪个更适合用于二进制文件:reinterpret_cast 还是 c_str()?为什么?
就个人而言,似乎 c_str() 更好......
谢谢你们 :)