【问题标题】:Read from binary file where double and string were saved从保存 double 和 string 的二进制文件中读取
【发布时间】:2019-11-20 01:59:32
【问题描述】:

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

这是我的代码:

int main(){



    double nb = 26.2254;
    std::string str = "Hello";



    std::ofstream myfile("test.bin", std::ios::out | std::ios::binary);

    myfile.write(str.c_str(), str.length());
    myfile.write((char*)&nbstr, sizeof(nb));
    myfile.write(str.c_str(), str.length());
    myfile.write(str.c_str(), str.length());

    myfile.close();


}

我在将nb 写入文件之前将其转换为字符串,这样我就可以只读字符串。不知道有没有好办法。

int main(){



    double nb = 26.2254;
    std::string nbstr;
    std::string str = "Hello";
    std::ostringstream ss;

    nbstr = std::to_string(nb);


    std::ofstream myfile("test.bin", std::ios::out | std::ios::binary);

    myfile.write(str.c_str(), str.length());
    myfile.write(nbstr.c_str(), nbstr.length());
    myfile.write(str.c_str(), str.length());
    myfile.write(str.c_str(), str.length());

    myfile.close();

    std::ifstream openfile("test.bin", std::ios::in | std::ios::binary);

    ss << openfile.rdbuf();

    openfile.close();


    std::cout << ss.str() << std::endl;
}


【问题讨论】:

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

标签: c++ file binary


【解决方案1】:

对于二进制文件,您需要指定写入字符串的长度。可以通过显式写入长度来完成,即

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(),不如使用&lt;&lt;&gt;&gt; 运算符更容易,如下所示:

myfile << str;
myfile << nb;

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2016-08-25
    • 2014-10-18
    • 2017-10-18
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多