Saving structure to a file

This is a discussion on Saving structure to a file within the C++ Programming forums, part of the General Programming Boards category; Hi all, I have a very simple array of structures. Structure is as follows Code: struct StockItem { int code; ...

  1. #1
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164

    Saving structure to a file

    Hi all,

    I have a very simple array of structures. Structure is as follows
    Code:
    struct StockItem
    {
        int code;
        char desc[20];
        float price;
    };
    When this populate my items using this data structures, I need to save these items to disk.

    Also, once these items have been saved to disk, I need to reload them back into my program the next time I start it up.

    Can anyone help me with this please?
    I have made an attempt, but am still pretty new to programming and can't get it to work and I think I am going down the wrong path.

    Code as follows:
    Code:
    void save_data(StockItem save)
    {
        fstream fp;
        
        fp.open("items.txt", ios::out | ios::app);
        if (!fp)
        {
            cout << "\n*** Error opening file ***\n";
            //exit(0);
        }
        fp << save.code;
        for(unsigned short i = 0; i < 20; i++)
        {
            fp.put(save.desc[i]);
        }
        fp << save.price;
    
        fp.close();
    }
    
    
    void print_data(void)
    {
        fstream fp;
        
        fp.open("items.txt", ios::in);
        if (!fp)
        {
            cout << "\n*** Error opening file ***\n";
            //exit(0);
        }
        cout << fp;
    
        fp.close();
    }
    All help would be greatly appricieted.

    Thanks

  2. #2
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    Code:
    void read_data(StockItem save, string file_name)
    {
        ifstream fp;
        fp.open(file_name.c_str());
        if (!fp)
        {
            cout << "\n*** Error opening file ***\n";
            //exit(0);
        }
        fp >> save.code;
        for(unsigned short i = 0; i < 20; i++)
        {
            fp >> save.desc[i];
        }
        fp >> save.price;
    
        fp.close();
    }
    Didnīt test it, but should work. I just switched the << for >>.
    Nothing more to tell about me...
    Happy day =)

  3. #3
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    My original attempt I posted works. It saves the data into a text file....albeit in a very strange manner.

    I just need to be able to save the structures to a file, and read them back in again at a later date.

    I think my entire approach was wrong, and I am sure there must be an easy way.

  4. #4
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    I think tha your save function is ok! I couldnīt think in a better way to do it. What is wrong?
    Nothing more to tell about me...
    Happy day =)

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    One solution is binary mode.

    Kuphryn

  6. #6
    Registered User
    Join Date
    Aug 2003
    Posts
    1,197
    try this:
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    struct test
    {
    public:
    	test(int X, int Y) { x = X; y = Y; }
    	int GetX() { return x; }
    	int GetY() { return y; }
    	void SetX(int num) { x = num; }
    	void SetY(int num) { y = num; }
    private:
    	int x;
    	int y;
    };
    
    int main()
    {
    	test bla(5, 10);
    
    	ofstream fout("save.txt", ios::binary);
    	fout.write((char*)&bla, sizeof(bla));    // Saving
    	fout.close();
    	
    	test bu(1, 1);    // Where we want to load the saved structure
    	
    	ifstream fin("save.txt", ios::binary);
    	fin.read((char*)&bu, sizeof(bu));    // Loading
    	fin.close();
    }

  7. #7
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    I think my real problem is getting the structures back into the program.

    If I populate the program with say, 40 items, I want to be able to save them to disk, then write them back in again.

    I can save them, but I don't know how to write them back into the program.

    Say my array of structures uses 'ctr' to identify the items.

    stock[ctr].code;
    stock[ctr].desc;
    stock[ctr].price;

    If I enter many items and then save them to a text file using the function I wrote, I do appear to get data in my text file. (although it is not what I expected).

    However, what I now need to do, is get this data in text file back into my program the next time the program is restarted.
    I need each part that was originally in the each element of the structure to go back in the data structure in the correct elements.

    I hope that makes sense, its a little hard to explain.

  8. #8
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    Shatki, I only saw your post after I made mine. I'll look into that method now. Thanks.

  9. #9
    WDT
    WDT is offline
    Tha 1 Sick RAT
    Join Date
    Dec 2003
    Posts
    271
    shakti hit it straight on the head.
    A hundred Elephants can knock down the walls of a fortress... One diseased rat can kill everyone inside

  10. #10
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Originally posted by eth0
    I think my real problem is getting the structures back into the program.

    If I populate the program with say, 40 items, I want to be able to save them to disk, then write them back in again.

    I can save them, but I don't know how to write them back into the program.

    Say my array of structures uses 'ctr' to identify the items.

    stock[ctr].code;
    stock[ctr].desc;
    stock[ctr].price;

    If I enter many items and then save them to a text file using the function I wrote, I do appear to get data in my text file. (although it is not what I expected).

    However, what I now need to do, is get this data in text file back into my program the next time the program is restarted.
    I need each part that was originally in the each element of the structure to go back in the data structure in the correct elements.

    I hope that makes sense, its a little hard to explain.
    Once you have the structure array populated, output the entire array in one binary output.

    Then read the file in in one biary input, which should fill the array as it was loaded.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  11. #11
    Registered User
    Join Date
    Jul 2003
    Posts
    59
    word of advice.
    if you are going to make your program portable, don't write the whole struct at once.
    Instead write its elements one by one.

  12. #12
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Originally posted by erikj
    word of advice.
    if you are going to make your program portable, don't write the whole struct at once.
    Instead write its elements one by one.
    Why? Do different compilers write binary differently when using standard I/O functions?
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  13. #13
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Why? Do different compilers write binary differently when using standard I/O functions?
    Yes, actually they do. Binary read and write (even with standard functions) is a one-to-one mapping of memory. This means that the data written depends on a lot of platform-dependent details. This wouldn't be a problem with compilers on the same platform except for the fact that different compilers use different padding in structures.
    My best code is written with the delete key.

  14. #14
    Registered User
    Join Date
    Jul 2003
    Posts
    59
    Yes. When dealing with different platforms endianness can also cause problems.

    I'm not sure but in c++ the vtable is also saved and that would be a waste to fwrite.

  15. #15
    Registered User
    Join Date
    Dec 2003
    Posts
    4
    .
    Last edited by Gedi; 01-05-2004 at 03:59 AM.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  2. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. File Processing using structure and functions
    By Randoon in forum C Programming
    Replies: 1
    Last Post: 12-04-2002, 06:44 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 02:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21