11

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

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

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

4

7 回答 7

11

要将 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-string 或等效 string::c_str() 调用末尾的 '\0' 标记,但这不是一个好主意,因为

  1. 您必须逐个字符地读取字符串字符以检查 null
  2. std::string 可以合法地包含一个空字节(尽管它确实不应该,因为对 c_str() 的调用会令人困惑)。
于 2016-05-04T19:03:12.190 回答
10

线

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

是不正确的

sizeof(string)不返回字符串的长度,它返回字符串类型的大小(以字节为单位)。

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

你可以简单地写

outfile << text;

反而。

于 2012-06-03T19:51:46.640 回答
3
  • 你为什么使用指向std::string类的指针?
  • 您不应该使用sizeofwith std::string,因为它返回std::string对象的大小,而不是内部字符串的实际大小。

你应该试试:

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

或者

outfile << text;
于 2012-06-03T19:52:46.310 回答
1

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

于 2012-06-03T19:49:04.800 回答
0

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

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

于 2018-10-22T11:18:36.593 回答
0

您的代码错误 您用于写入和读取文件的方式错误 文件扩展名错误 您正在尝试读取文本文件.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();

试试这个它会工作

于 2017-05-21T13:21:58.797 回答
-1

试试这个代码片段。

/* 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();
  }

是一个很好的例子。

于 2012-09-25T05:07:56.577 回答