C++ 从保存双精度和字符串的二进制文件中读取

C++ 从保存双精度和字符串的二进制文件中读取,c++,file,binary,C++,File,Binary,我在一个二进制文件中写入双精度和字符串。我想读取此文件,但由于数据类型混合,如何正确读取文件内容?(知道行是字符串还是双精度) 这是我的代码: intmain(){ 双nb=26.2254; std::string str=“Hello”; std::ofstreammyfile(“test.bin”,std::ios::out | std::ios::binary); write(str.c_str(),str.length()); write((char*)&nbstr,sizeof(nb)

我在一个二进制文件中写入双精度和字符串。我想读取此文件,但由于数据类型混合,如何正确读取文件内容?(知道行是字符串还是双精度)

这是我的代码:

intmain(){
双nb=26.2254;
std::string str=“Hello”;
std::ofstreammyfile(“test.bin”,std::ios::out | std::ios::binary);
write(str.c_str(),str.length());
write((char*)&nbstr,sizeof(nb));
write(str.c_str(),str.length());
write(str.c_str(),str.length());
myfile.close();
}
在将
nb
写入文件之前,我将其转换为字符串,这样我就可以只读字符串。我不知道这是不是个好办法

intmain(){
双nb=26.2254;
std::字符串nbstr;
std::string str=“Hello”;
std::ostringstream ss;
nbstr=std::to_字符串(nb);
std::ofstreammyfile(“test.bin”,std::ios::out | std::ios::binary);
write(str.c_str(),str.length());
write(nbstr.c_str(),nbstr.length());
write(str.c_str(),str.length());
write(str.c_str(),str.length());
myfile.close();
std::ifstream openfile(“test.bin”,std::ios::in | std::ios::binary);

对于二进制文件,您需要指定写入字符串的长度

size_t len = str.length();
myfile.write(&len, sizeof(len));
myfile.write(str.c_str(), len);
或者您可以只在字符串的末尾写入
'\0'
-终止字符,这是
c_str()
提供的帮助,因此您只需要编写它:

myfile.write(str.c_str(), str.length() + 1);
阅读时,您可以先阅读长度,或者在文件中搜索
'\0'

顺便说一句,与其使用
write()
read()
,不如使用
运算符,如下所示:

myfile << str;
myfile << nb;

myfile对于字符串,通常的方法是在实际数据之前预先指定长度。如果您不知道获取数据的顺序,可以在每个项之前预先指定一个标识符,并根据该标识符获取数据。您不能将二进制文件视为包含文本,这最终是在将其读入
ostringstream
。还有一个问题,除非您编写的文本具有事先已知的固定长度,否则您还需要保存实际长度,以便知道要读取的字符数。通常,不要使用二进制文件,文本文件通常更易于处理,以便于简单使用。