将字符串写入二进制文件C ++

时间:2012-06-03 19:42:45

标签: c++ string file malloc

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

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();

我无法让它发挥作用。对不起,我只是绝望了。谢谢!

7 个答案:

答案 0 :(得分:8)

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

不正确

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

也不使用C强制转换将文本强制转换为char*,您可以使用相应的成员函数text.c_str()

来获取char *

你可以简单地写

outfile << text;

代替。

答案 1 :(得分:4)

要将std :: string写入二进制文件,首先需要保存字符串长度:

std::string str("whatever");
size_t size=str.size();
outfile.write(&size,sizeof(size);
outfile.write(&str[0],size);

要读取它,请反转该过程,首先调整字符串的大小,以便有足够的空间:

std::string str;
size_t size;
infile.read(&size, sizeof(size));
str.resize(size);
infile.read(&str[0], size);

因为字符串具有可变大小,除非您将该大小放在文件中,否则您将无法正确检索它。您可以依赖保证位于c字符串末尾或等效字符串:: c_str()调用的'\ 0'标记,但这不是一个好主意,因为 1.你必须通过字符检查字符串字符来检查null 2.一个std :: string可以合法地包含一个空字节(虽然它实际上不应该因为对c_str()的调用而引起混淆)。

答案 2 :(得分:2)

1)为什么你使用指向字符串类的指针? 2)你不应该在字符串中使用sizeof,它返回对象的大小而不是字符串的大小。

你应该尝试:

string text = "Text";
outfile.write(text.c_str(), text.size());

outfile<<text;

答案 3 :(得分:0)

也应该使用c_str()来获取char指针,而不是直接疯狂的演员。

答案 4 :(得分:0)

试试这段代码。

/* writing string into a binary file */

  fstream ifs;
  ifs.open ("c:/filename.exe", fstream::binary | fstream::in | fstream::out);

  if (ifs.is_open())
  {
   ifs.write("string to binary", strlen("string to binary")); 
   ifs.close();
  }

Here就是一个很好的例子。

答案 5 :(得分:0)

你的代码错误,你用来写&amp;读取文件 您尝试读取文本文件.txt时出现文件扩展名错误 正确的代码

写入文件

std::string text = "Text";
ofstream outfile("myfile.dat", ofstream::binary | ios::out);
outfile.write(&text,sizeof (string));//can take type
outfile.write(&text,sizeof (text));//can take variable name
outfile.close();

阅读文件

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

试试这个会起作用

答案 6 :(得分:0)

我有同样的问题。我在这里找到了完美的答案:Write file in binary format

关键问题:写出时使用string :: length来获取字符串的长度,并在读取字符串之前使用resize()。对于阅读和写作,都使用mystring.c_str()代替字符串本身。