2011-03-26 20 views
5

所以我用这个代码写入文件(刚才的测试,我会写一个关卡编辑器版本): 写串以二进制方式file


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; 
} 

我的代码m使用加载它是这样的:

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和错误,当我加载图像。我也在它的长度前加上字符串。 将字符串写入二进制文件的正确方法是什么? 什么是CORRE

回答

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个字符被写入,然后你得到一些垃圾。

+0

这工作,除了因为某些奇怪的原因在字符串的末尾添加了一个额外的g。我会尽量减小大小到11,看看是否有任何问题。 – Chris 2011-03-26 14:18:56

+0

空字符不应该是OP代码的问题(有您的更正)。它永远不会假定''\ 0''作为一个字符串终结符,它从不使用C风格的字符串。 – 2011-03-26 14:19:47

+0

好吧,将长度设置为11。 – Chris 2011-03-26 14:20:33