Thread: Reconstructing a vector saved in a binary file..

  1. #1
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968

    Reconstructing a vector saved in a binary file..

    I've stumbled on this little example: vector::reserve - C++ Reference

    What I'm trying to do is stick a bunch of employee objects in a vector, save it to a file, and load the file and use the vector next time I open the program, a database of sorts.

    Code:
    void save_data()
    {
        ofstream employee_data;
        employee_data.open("employee_data.bin", ios::binary);
        if (employee_data.is_open())
        {
            cout << "File successfully opened and initialized." << endl;
            if(!employees.empty())
            {
                employee_data.write(reinterpret_cast<char*>&employees[0], employees.size() * sizeof(employee));
                cout << "Data successfully written to the file." << endl;
            }
            else
            {
                cout << "That vector is empty bro...." << endl;
            }
        }
        else
        {
            cout << "This didn't work noob!" << endl;
        }
    }
    
    void get_data()
    {
        ifstream employee_data;
        employee_data.open("employee_data.bin", ios::binary);
        if(employee_data.is_open())
        {
            //start copying data to memory
        }
        else
        {
            //something went wrong, probably can't find file, or doesn't exist
        }
    }
    I'm not 100% sure how to go about copying the data from the file so that I can use the data in memory like I would any other vector.
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    What do your employee objects look like data-members-wise? Unless they are strictly POD you are going to have issues writting/reading to/from a file like you are attempting.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Like this?

    Code:
    class employee
    {
    public:
    	employee(std::string, float);
    	const std::string& get_name();
    	const float& get_payrate();
    	const std::string& get_gender();
    	const std::string& get_startdate();
    	const std::string& get_enddate();
    
    	void set_name(std::string);
    	void set_payrate(float);
    	void set_gender(std::string);
    	void set_startdate(std::string);
    	void set_enddate(std::string);
    private:
    	std::string name;
    	float payrate;
    	std::string gender;
    	std::string startdate;
    	std::string enddate;
    	bool active;
    };
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Serialization is what you are looking for (Serialization).

  5. #5
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Do I really need to install boost to do serialization, isn't there a standard?
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    You do not "have" to install boost to do serialization, but no there is no "standard". To successfully read and write information to a binary file the data must be read exactly as it was written. The problem with std::string is that every string can contain a different number of characters. You need someway of knowing how many bytes this string contains when written so you can read back the same number of bytes.

    Have you considered just using a text file instead of the binary file?

    Jim

  7. #7
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    There is no standard one. There are also other libraries in the link I posted.

  8. #8
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Well, I do not want to use a text file because ultimately I want my code to be a bit more re-usable.

    And honestly boost seems to be the best thing for this, as it is minimally intrusive, as I've been reading. I also don't really want the files to be changed outside of the application.
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Shamino View Post
    Well, I do not want to use a text file because ultimately I want my code to be a bit more re-usable.
    That is a rather (ahem) novel excuse for wanting to write a binary file rather than a text file.

    If you write a text file the, in practice, there is a high likelihood that the contents can be read correctly when the code is rebuilt using another compiler, or ported to another operating system. Conversely, if you write a binary file, there is a high likelihood that the contents can not be read correctly unless you stick only to one compiler.

    If you care about reusability, the easiest approach is to use a text file. It is possible to do it with a binary file, but significantly more effort (for example, rigorously defining a protocol that describes what the content of a binary file means) to do so.

    Writing binary files does not prevent files being changed outside your application. It can actually increase the impact of data corruption (for example, if a problem occurs with your hard drive) unless the binary format is designed with fault tolerance in mind. If someone is determined to change your data files, they will work out a way.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I agree with grumpy; text is a more robust form of serialization.

    However, it's also generally more work, for you and the executable. So two valid excuses not to do so would be:
    - I don't consider it necessary because of the scope of the task.
    - There is some highly significant performance aspect involved.

    The nature of STL containers partially nullifies the second excuse, because the most efficient option -- writing a whole vector object straight to a file -- is not feasible*. Instead, you have to write the contents of the vector to a file. In which case, using text is only another intermediate step.

    * neither is writing an employee object, or any kind of object AFAIK. What you should do is write an employee.toString method to serialize the data members to text, then iterate thru the vector, call that for each employee, and write each string to the file using some delimiter between records (eg, a double '\n'). You then write an extra constructor that takes a single string (formatted the way toString does) for de-serialization, and use that when you load the vector from a file.
    Last edited by MK27; 02-02-2012 at 04:19 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Quote Originally Posted by MK27 View Post
    I agree with grumpy; text is a more robust form of serialization.

    However, it's also generally more work, for you and the executable. So two valid excuses not to do so would be:
    - I don't consider it necessary because of the scope of the task.
    - There is some highly significant performance aspect involved.

    The nature of STL containers partially nullifies the second excuse, because the most efficient option -- writing a whole vector object straight to a file -- is not feasible*. Instead, you have to write the contents of the vector to a file. In which case, using text is only another intermediate step.

    * neither is writing an employee object, or any kind of object AFAIK. What you should do is write an employee.toString method to serialize the data members to text, then iterate thru the vector, call that for each employee, and write each string to the file using some delimiter between records (eg, a double '\n'). You then write an extra constructor that takes a single string (formatted the way toString does) for de-serialization, and use that when you load the vector from a file.
    This sounds way more fun to do than all of the other suggestions. I can just figure a way to send a stringstream to the ofstream, and create the stringstream from the data members in the employee file, which is basically a bunch of strings anyways.
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bad characters in excel saved CSV file
    By rogster001 in forum C++ Programming
    Replies: 11
    Last Post: 05-27-2011, 09:59 AM
  2. Scoreboard saved in .txt file?
    By Newklear in forum C Programming
    Replies: 14
    Last Post: 03-21-2011, 08:06 PM
  3. Writing contents of an std::vector to a binary file! ;o)
    By shrink_tubing in forum C++ Programming
    Replies: 7
    Last Post: 08-22-2010, 06:32 AM
  4. Location of Saved File
    By loopshot in forum C++ Programming
    Replies: 13
    Last Post: 01-22-2006, 11:26 PM
  5. reading saved file
    By firefly in forum C++ Programming
    Replies: 1
    Last Post: 07-09-2005, 01:24 AM