Thread: Saving structure to a file

  1. #16
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    Can anyone please help me with getting this running.
    I have been trying to get the read / write to file fuctionality in this code working for days now and I am running out of hair to pull out

    I have a lot more code to get into this program, but I cannot move on until this section is working.

    Sorry to have to ask like this, but I am running out of ideas as I don't know any programmers to ask for help.

    Thanks for your help, code is as follows, the problem sections are at the bottom:

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    struct StockItem
    {
        int code;
        char desc[20];
        float price;
    };
    
    /*struct bill_line
    {
        StockItem product;
        float weight;
        float cost;
    };
    
    struct bill
    {
        bill_line items[20];
        int num_lines;
    };*/
    
    void disp_menu(void);
    struct StockItem enter_data();
    void see_stock(StockItem stock[125], int num_items);
    void save_data(StockItem save);
    StockItem (* load_data) (void);
        
    
    main()
    {
        StockItem stock[125];
        int ans;
        int num_items = 0;
        
        do
        {
            do
            {
                disp_menu();
                cin >> ans;
            } while ((ans<1) || (ans>6));
            
            switch (ans)
            {
                case 1: 
                    stock[num_items] = enter_data();
                    num_items++;
                    break; 
                case 2: 
                    see_stock(stock, num_items);
                    break;
                case 3:
                    save_data(*stock);
                    
                        break;
                case 4:
                    stock = (* load_data) (void);
                default:
                    break;
            } 
        }while (ans!=5);
            
        return 0;
    
        system("PAUSE");
        return 0;
    }
    
    void disp_menu()
    {
        cout << "\n*** The Corner Shop ***\n\n";
        cout << "Select an option: \n\n";
        cout << "\t1. Enter new stock " << endl;
        cout << "\t2. See current stock " << endl;
        cout << "\t3. Save stock to disk " << endl;
        cout << "\t4. Load stock from disk " << endl;
        cout << "\t5. Exit \n" << endl;
        cout << "option> ";
    }
    
    StockItem enter_data()
    {
        StockItem stock_item;
        
        cout << "\n\nWhat is the product code: ";
        cin >> stock_item.code;
        cout << "What is the product description: ";
        fflush(stdin);
        cin.getline(stock_item.desc, 20);
        cout << "What is the product price: ";
        cin >> stock_item.price;  
        
        return (stock_item);
    }
    
    void see_stock(StockItem stock[125], int num_items)
    {
        int ctr;
        char ret;
    
        cout << "\n\nHere is the stock listing:\n\n";
        for (ctr = 0; ctr < num_items; ++ctr)
        {
            cout << "Item " << ctr+1 << endl;
            cout << "Product Code: " << stock[ctr].code <<  endl;
            cout << "Product Description: " << stock[ctr].desc << endl;
            cout << "Price: " << stock[ctr].price << endl;
            cout << "------------------------------------------------\n";
        }
        cout << "Press any key to return to the menu";
        if (cin >> ret)
        return;
    }
    
    //Problem sections
    void save_data(StockItem save)
    {
        ofstream fout("items.txt", ios::binary);
        if (!fout)
        {
            cout << "\n*** Error opening file ***\n";
        }
        
        fout.write((char*)&save, sizeof(save));
        fout.close();
    }
    
    
    StockItem (* load_data) (void)
    {
        ifstream fin("save.txt", ios::binary);
        if (!fin)
        {
            cout << "\n*** Error opening file ***\n";
        }
        fin.read((char*)&save, sizeof(save));
        fin.close();
        return &save;
    }

  2. #17
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Well one thing I saw on the fly (just skimmed through your code fast)
    Code:
    void save_data(StockItem save)
    {
        ofstream fout("items.txt", ios::binary);    // Here you save to items.txt
        if (!fout)
        {
            cout << "\n*** Error opening file ***\n";
        }
        
        fout.write((char*)&save, sizeof(save));
        fout.close();
    }
    
    
    StockItem (* load_data) (void)
    {
        ifstream fin("save.txt", ios::binary);    // But here you try to load from save.txt
        if (!fin)
        {
            cout << "\n*** Error opening file ***\n";
        }
        fin.read((char*)&save, sizeof(save));
        fin.close();
        return &save;
    }
    Or do you get any other errors???

  3. #18
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    oops hadn't seen that.

    Although that wasn't the cause. I can't get the code to compile any more. All this pointer to functions etc gets confusing for beginners.

    I still need help to get this working

  4. #19
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Here is a working program you can have a look at (Note; I am almost certain that this isnt the best aproach with this method but atleast its working)
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    struct test
    {
    public:
    	test(int X, int Y) { x = X; y = Y; }
    	test() {}
    	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;
    };
    
    void save(test* tosave);
    test* load(test toload[]);
    
    int main()
    {
    	test bla[15];
    	bla[0].SetX(3);
    	bla[0].SetY(3);
    	bla[7].SetX(14);
    	bla[7].SetY(19);
    	save(bla);
    
             test ba[15];
    	test* bu = load(ba);
    	
             cout << bu[0].GetX() << " " << bu[0].GetY() << endl;
    	cout << bu[7].GetX() << " " << bu[7].GetY() << endl;
    }
    
    void save(test* tosave)
    {
    	ofstream fout("save.txt", ios::binary);
    	if(!fout)
    	{
    		cout << "\n*** Error opening the file! ***\n";
    		return;
    	}
    	fout.write((char*)&tosave, sizeof(tosave));
    	fout.close();
    }
    
    test* load(test* toload)
    {
    	ifstream fin("save.txt", ios::binary);
    	if(!fin)
    	{
    		cout << "\n** Error opening the file! **\n";
    		return NULL;
    	}
    	fin.read((char*)&toload, sizeof(toload));
    	fin.close();
    	return toload;
    }
    Last edited by Shakti; 01-05-2004 at 09:43 AM.

  5. #20
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    I have been sat here now for another 7 hours trying to get these functions to work.

    I don't think I can get them running without some major help.

    Can somebody please please get these functions working so I can understand how it works. I would possibly be the most grateful person in the world, I don't think I can take much more..... ........i've been at the same 2 functions for 2 days solid...lol

    Here is one of my later attempts. I "think" it is the closets so far, but I have a feeling the reason its not working is due to the way the data is being passed to the functions. I have no idea how to fix it.

    Thank you

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    struct StockItem
    {
         int code;
          char desc[20];
          float price;
    }stock[125];
    
    /*struct bill_line
    {
        StockItem product;
        float weight;
        float cost;
    };
    struct bill
    {
        bill_line items[20];
        int num_lines;
    };*/
    
    void disp_menu(void);
    struct StockItem enter_data();
    void see_stock(StockItem stock[125], int num_items);
    void save_data(StockItem * tosave);
    StockItem *load_data(StockItem toload[]);
    
    int main()
    {
          //StockItem stock[125];
         int ans;
         int num_items = 0;
         
       do
            
       {
             
          do
                
          {
                  disp_menu();
                  cin >> ans;
             } while((ans < 1) || (ans > 6));
             switch (ans)
                
          {
             case 1:
                  stock[num_items] = enter_data();
                  num_items++;
                  break;
             case 2:
                  see_stock(stock, num_items);
                  break;
             case 3:
                  save_data(stock[ctr]);
                  break;
             case 4:
                
          {
                   //StockItem temp[125];
                     StockItem * eerrmm = load_data(stock);
                  break;
             }
             default:
                  break;
             }
         } while(ans != 5);
         return 0;
    }
    
    void disp_menu()
    {
         cout << "\n*** The Corner Shop ***\n\n";
         cout << "Select an option: \n\n";
         cout << "\t1. Enter new stock " << endl;
         cout << "\t2. See current stock " << endl;
         cout << "\t3. Save stock to disk " << endl;
         cout << "\t4. Load stock from disk " << endl;
         cout << "\t5. Exit \n" << endl;
         cout << "option> ";
    }
    
    StockItem enter_data()
    {
         StockItem stock_item;
         cout << "\n\nWhat is the product code: ";
         cin >> stock_item.code;
         cout << "What is the product description: ";
         fflush(stdin);
         cin.getline(stock_item.desc, 20);
         cout << "What is the product price: ";
         cin >> stock_item.price;
         return (stock_item);
    }
    void see_stock(StockItem stock[125], int num_items)
    {
         int ctr;
         char ret;
         cout << "\n\nHere is the stock listing:\n\n";
         for(ctr = 0; ctr < num_items; ++ctr)
            
       {
             cout << "Item " << ctr + 1 << endl;
             cout << "Product Code: " << stock[ctr].code << endl;
             cout << "Product Description: " << stock[ctr].desc << endl;
             cout << "Price: " << stock[ctr].price << endl;
             cout << "------------------------------------------------\n";
         }
         cout << "Press any key to return to the menu";
         if(cin >> ret)
             return;
    }
    
    //Problem sections
    void save_data(StockItem * tosave)
    {
         ofstream fout("items.txt", ios::binary);
         if(!fout)
            
       {
             cout << "\n*** Error opening file ***\n";
         }
         fout.write((char *) &tosave, sizeof(tosave));
         fout.close();
    }
    
    StockItem *load_data(StockItem * toload)
    {
         ifstream fin("items.txt", ios::binary);
         if(!fin)
            
       {
             cout << "\n*** Error opening file ***\n";
         }
         fin.read((char *) &toload, sizeof(toload));
         fin.close();
         cout << toload;
         return toload;
    }

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

    ***Solved***

    Thought I'd post this here for future reference in case anyone is searching.

    Along with the help of a programmer on my Linux mailing list, here is a pretty simple answer to what I was trying to do.

    Write only as many items to the file as you have in your array.
    When you reading the items back from file you can count them until you reaching the end of file. With this value you can set the num_items variable.


    **Working Code**
    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    struct StockItem
    {
        int code;
        char desc[20];
        float price;
    }stock[125];
    
    /*struct bill_line
    {
        StockItem product;
        float weight;
        float cost;
    };
    
    struct bill
    {
        bill_line items[20];
        int num_lines;
    };*/
    
    void writeToDisk( StockItem*, int );
    int readFromDisk( StockItem* );
    void disp_menu(void);
    struct StockItem enter_data();
    void see_stock(StockItem stock[125], int num_items);
    
    int main()
    {
        int ans, ctr;
        int num_items = 0;
    
        do
        {
            do
            {
                disp_menu();
                cin >> ans;
            } while ((ans<1) || (ans>6));
    
            switch (ans)
            {
                case 1:
                    stock[num_items] = enter_data();
                    num_items++;
                    break;
                case 2:
                    see_stock(stock, num_items);
                    break;
                case 3:
                    writeToDisk( stock, num_items );
    //                                  ^^^^^^^^^ <-- writing NOT the whole array
    //                                                to disk.
                    break;
                case 4:
                    num_items = readFromDisk( stock );
    //              ^^^^^^^^^ <---- setting the number items we read from file
                    break;
                default:
                    break;
            }
        }while (ans!=5);
    
        return 0;
    }
    
    void writeToDisk( StockItem* array, int numOfItems )
    {
        ofstream outfile( "items.txt" );
        for( int index = 0; index < numOfItems; index++ )
            outfile.write( (char*)&array[index], sizeof(StockItem) );
    }
    
    int readFromDisk( StockItem* array )
    {
        int numOfItems = 0;
        ifstream infile( "items.txt" );
        StockItem tmp_stockItem;
        // read from the file until we are reaching the eof
        while( infile.read( (char*)&tmp_stockItem, sizeof(tmp_stockItem) ) )
        {
            // after a successfull read we storing the the item into the array
            memcpy( &array[numOfItems], 
                &tmp_stockItem, 
                sizeof( array[numOfItems] ) );
            numOfItems++;
        }
        // returning the number of array items we read from the file
        return numOfItems;
    }
    
    void disp_menu()
    {
        cout << "\n*** The Corner Shop ***\n\n";
        cout << "Select an option: \n\n";
        cout << "\t1. Enter new stock " << endl;
        cout << "\t2. See current stock " << endl;
        cout << "\t3. Save stock to disk " << endl;
        cout << "\t4. Load stock from disk " << endl;
        cout << "\t5. Exit \n" << endl;
        cout << "option> ";
    }
    
    StockItem enter_data()
    {
        StockItem stock_item;
    
        cout << "\n\nWhat is the product code: ";
        cin >> stock_item.code;
        cout << "What is the product description: ";
        cin.ignore();
        cin.getline(stock_item.desc, 20);
        cout << "What is the product price: ";
        cin >> stock_item.price;
    
        return (stock_item);
    }
    
    void see_stock(StockItem stock[125], int num_items)
    {
        int ctr;
        char ret;
    
        cout << "\n\nHere is the stock listing:\n\n";
        for (ctr = 0; ctr < num_items; ++ctr)
        {
            cout << "Item " << ctr+1 << endl;
            cout << "Product Code: " << stock[ctr].code <<  endl;
            cout << "Product Description: " << stock[ctr].desc << endl;
            cout << "Price: " << stock[ctr].price << endl;
            cout << "------------------------------------------------\n";
        }
    }

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, 07:44 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM