简体   繁体   English

C++ -- 从二进制文件中读取动态分配的向量

[英]C++ -- reading dynamically allocated vectors from a binary file

I am working on a problem, and I am not sure if I'm doing this properly, or if I even have the right approach at all.我正在解决一个问题,但我不确定我这样做是否正确,或者我什至是否有正确的方法。 My code, so far, just gives me segfaults.到目前为止,我的代码只给我段错误。

I have a simple little receipt writing program to practice some C++ concepts, one of them being file i/o in binary.我有一个简单的小收据编写程序来练习一些 C++ 概念,其中之一是二进制文件 i/o。 I have a couple arrays holding data (one holding strings of a service type, the other holding corresponding double costs).我有一对 arrays 持有数据(一个持有服务类型的字符串,另一个持有相应的双倍成本)。 I have a little menu, and the writing in binary part goes fine.我有一个小菜单,二进制部分写得很好。 However, I am not sure how to read these back from the file.但是,我不确定如何从文件中读回这些内容。

I am currently using a structure to hold various data members (customer's name, total charges, etc.), and I want to write all of the services they chose, along with their corresponding prices, to a file, and then be able to read them back.我目前正在使用一个结构来保存各种数据成员(客户姓名、总费用等),我想将他们选择的所有服务及其相应的价格写入一个文件,然后能够读取他们回来了。 These are currently stored in vectors in the structure.这些当前存储在结构中的向量中。

I think I understand how to read/write strings to/from a binary file (write the length of the string, then the data, then read the length back, then read that many bytes into a string).我想我了解如何从二进制文件读取/写入字符串(写入字符串的长度,然后是数据,然后读回长度,然后将那么多字节读入字符串)。 But how do I do this with a vector?但是我如何使用矢量来做到这一点? I understand how it can be done with, say, a vector of fixed-size members (ie ints), but what about a vector of strings?我知道如何使用固定大小成员(即整数)的向量来完成它,但是字符串向量呢? In this case, the members do not have a set size, so I am not sure how to read them back.在这种情况下,成员没有设置大小,所以我不确定如何读回它们。

Is this even possible?这可能吗? If anyone could point me in the right direction, that would be extremely helpful.如果有人能指出我正确的方向,那将非常有帮助。 There was a similar forum posting a year or so ago, but it didn't help me much.大约一年前有一个类似的论坛帖子,但对我没有太大帮助。

tl;dr -- How do I read a variable-size vector of variable-length strings from a binary file? tl;dr——如何从二进制文件中读取可变长度字符串的可变大小向量?

You need to package or encapsulate your data into objects and to serialize them out, as Mark pointed it out using http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html .您需要 package 或将数据封装到对象中并将它们序列化,正如 Mark 使用http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html指出的那样。 You can find examples and detailed help there.您可以在那里找到示例和详细帮助。 Search for a very simple case.搜索一个非常简单的案例。 :) :)

Edit: I have done for you a quick and dirty example.编辑:我已经为你做了一个快速而肮脏的例子。 Enjoy.享受。 (Apologies for the formatting.) (为格式道歉。)

#include <cstddef> // NULL
#include <iomanip>
#include <iostream>
#include <fstream>
#include <iterator>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>

class family_names
{
    friend class boost::serialization::access;
    std::vector<std::string> m_names;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
    ar & m_names;
    }

    friend std::ostream & operator<<(std::ostream &os, const family_names& fn);

    public:
family_names(const std::vector<std::string>& names)
    : m_names(names)
{}

family_names() {}
    };

    std::ostream & operator<<(std::ostream &os, const family_names& fn)
    {
std::ostream_iterator<std::string> out_it (std::cout,", ");
std::copy(fn.m_names.begin(), fn.m_names.end(), out_it);
return os;
    }

    void save(const family_names &s, const char * filename){
// make an archive
std::ofstream ofs(filename);
boost::archive::text_oarchive oa(ofs);
oa << s;
    }

    void restore(family_names &s, const char * filename)
    {
// open the archive
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);

// restore the family names from the archive
ia >> s;
    }

    int _tmain(int argc, _TCHAR* argv[])
    {

std::vector<std::string> vec_names;
vec_names.push_back("Jason");
vec_names.push_back("Mark");
vec_names.push_back("Ludmilla");


family_names names(vec_names);
std::string filename = "c:\\Dev\\demofile.txt";

std::cout << names << std::endl;
save(names, filename.c_str());

family_names names_back;
restore(names_back, filename.c_str());
std::cout << names_back << std::endl;

return 0;
  }

To paraphrase:换句话说:

> How do I read the length back, then read that many bytes into a string with a vector? > 我如何读回长度,然后将那么多字节读入带有向量的字符串中?

One string at a time:一次一个字符串:

// Untested
std::vector<std::string> ReadSomeStrings(std::istream& inFile, size_t howMany) {
  std::vector<std::string> result;
  for(int i = 0; i < howMany; ++i) {
    std::size_t len;
    is.read(&len, sizeof len);
    std::string s(len, '\0');
    is.read(&s[0], s.size());
    result.push_back(s);
  }
  return result;
}

I guess you use >> and << operators, I recommend you to try it with ofstream::write and ifstream::read for binary manipulation.我猜你使用 >> 和 << 运算符,我建议你尝试使用 ofstream::write 和 ifstream::read 进行二进制操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM