写入和读取字符串到二进制文件C ++ [英] write and read string to binary file C++

查看:136
本文介绍了写入和读取字符串到二进制文件C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Im在将字符串写入二进制文件时出现问题。这是我的代码:

Im having problems writing string into a binary file. This is my code:

ofstream outfile("myfile.txt", ofstream::binary);
std::string text = "Text";
outfile.write((char*) &text, sizeof (string));
outfile.close();

然后,我尝试读它,

char* buffer = (char*) malloc(sizeof(string));
ifstream infile("myfile.txt", ifstream::binary);    
infile.read(buffer, sizeof (prueba));
std::string* elem = (string*) buffer;
cout << *elem;
infile.close();

我只是无法工作。对不起,我只是绝望。谢谢!

I just cant get it to work. I am sorry, I am just desperate. Thank you!

推荐答案

outfile.write((char*) &text, sizeof (string));

不正确

sizeof(string)不返回字符串的长度,它返回字符串类型的sizeof字节。

sizeof(string) doesn't return the length of the string, it returns the sizeof the string type in bytes.

不要使用C转换将文本转换为 char * ,可以使用适当的成员函数 text.c_str()获取char *

also do not cast text to char* using a C cast, you can get hold of the char* by using the appropriate member function text.c_str()

您可以简单地写

outfile << text;

这篇关于写入和读取字符串到二进制文件C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆