D
D
Dmitry Demidov2014-01-28 09:20:39
C++ / C#
Dmitry Demidov, 2014-01-28 09:20:39

How to write data from a file to an array of structures?

Hello!
There is a file with lines of the form:
int1,string1,int2
There is a structure:

struct struct_name {
        int int1;
        string string1;
        int int2;
    };

And there is an array of such structures: It is
vector<struct_name>vector_name
necessary to write structures with the corresponding variables into the elements of the array.
That is, a vector_name[0]structure with variables from the first line of the file should be stored in.
I don't have much experience with C++ (almost none), I can't figure out how to do it right.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nekipelov, 2014-01-28
@nekipelov

If string1 were represented as char string1[123], then struct_name would be a POD type. In this case, it could read like this:

vector<struct_name> vector_name;
FILE *fp = fopen(...);
size_t size = ...

vector_name.resize(size);
fread(&vector_name[0], sizeof(struct_name), size, fp);

But since struct_name is not a POD, you will have to implement reading element by element. Or use something like boost.serialization:
struct struct_name {
    int int1;
    string string1;
    int int2;

    template<class Archive>
    void save(Archive & ar) const
    {
        ar  & int1;
        ar  & string1;
        ar  & int2;
    }
    template<class Archive>
    void load(Archive & ar)
    {
        ar & int1;
        ar & string1;
        ar & int2;
    }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question