所以我正在使用这段代码来编写文件(现在只是测试,我稍后会编写一个关卡编辑器):
int main()
{
ofstream file("level.bin", ios::binary);
int ents = 1; //number of entites
file.write((char*)&ents, sizeof(int));
float x = 300; //x and y coords
float y = 500;
file.write((char*)&x, sizeof(float));
file.write((char*)&y, sizeof(float));
int imglength = 12; //strings are prefixed by a length
file.write((char*)&imglength, sizeof(int));
string img = "platform.png"; //string
file.write(img.c_str(), sizeof(img.c_str()));
cout << "wrote\n";
return 0;
}
我用来加载它的代码是这样的:
void SceneManager::LoadScene(std::string filename)
{
std::ifstream file(filename.c_str(), std::ios::binary);
int ents;
file.read((char*)&ents, sizeof(int));
std::cout << ents << std::endl;
for(int i = 0; i < ents; i++)
{
//read x and y coords
float x;
float y;
file.read((char*)&x, sizeof(float));
file.read((char*)&y, sizeof(float));
std::cout << x << " " << y << std::endl;
int imglength;
file.read((char*)&imglength, sizeof(int));
std::cout << imglength << std::endl;
std::stringstream ss;
for(int k = 0; k <= imglength; k++)
{
//read string
char c;
file.read((char*)&c, sizeof(char));
ss << c;
}
std::string image = ss.str();
std::cout << image << std::endl;
phys_static ent;
Def edef;
edef.SetVal("x", x);
edef.SetVal("y", y);
edef.SetString("image", image);
ent.init(edef);
AddEntity(ent);
}
file.close();
}
除了字符串加载外,一切正常。我希望我写错了,因为它代替了platform.png,它显示了加载图像时的plattttttttt和错误。我也在字符串前面加上它的长度。 将字符串写入二进制文件的正确方法是什么? 什么是相关
答案 0 :(得分:10)
错误就在这一行:
file.write(img.c_str(), sizeof(img.c_str()));
你想要的是:
file.write(img.c_str(), img.size());
sizeof(img.c_str())
返回4,因为sizeof(char *)
(c_str()
的返回类型)在您的平台上为4。这意味着前4个字符被写入,然后你就会得到一些垃圾。