Storing An Object In Sequential File, C++

by Bar Zohan 5. April 2010 23:46

Here is the code for main.cpp;

Write function creates a new Data object, sets it's properties and write this object to a sequential file.

Main function reads the sequential file and restores the Data object.

#include <iostream>
using std::cerr;
using std::cin; 
using std::cout;
using std::endl;
using std::ios;

#include <iomanip>
using std::setw;


#include <fstream>        
using std::ofstream;
using std::fstream;
using std::ifstream;
using std::ostream;

#include <cstdlib>
using std::exit;

#include <string>
using std::string;

class Data
{
public:
    int accountnumber;
    string lastname;
    string firstname;
    double balance;
};

void Write();
void outputLine( ostream&, const Data & );

int main()
{

    ifstream inFile("output.txt",ios::in);
   
    if (!inFile)
    {
        cerr << "File could not be opened" << endl;
        exit(1);
    }

    Data data;
    char *dummy = (char*)new Data;
  
    inFile.read(dummy,sizeof(Data));
    inFile.read(reinterpret_cast<char*>(&data),sizeof(Data));

    outputLine(cout,data);
    delete [] dummy;

    return 0;
}

void outputLine( ostream &output, const Data &data )
{
output << data.accountnumber << " " << data.firstname<< " " << data.lastname << " " << data.balance << endl;
}

void Write()
{
    int accountnumber;
    string lastname;
    string firstname;
    double balance;


    fstream outputFile( "output.txt", ios::in | ios::out | ios::binary );

    if (!outputFile)
    {
        cerr << "file could not be opened" << endl;
        exit(1);
    }

    cout << "Enter account number (1 to 100, 0 to end input)\n? ";

    Data newData;
    cin >> accountnumber;

    while (accountnumber != 0 && accountnumber <= 100)
    {
        cout << "Enter last name, first name , balance \n?";
        cin >> lastname >> firstname >> balance;

        newData.accountnumber = accountnumber;
        newData.balance = balance;
        newData.firstname = firstname;
        newData.lastname = lastname;

        outputFile.seekp((newData.accountnumber - 1) * sizeof(Data));

        outputFile.write(reinterpret_cast<char *>(&newData),sizeof(Data));
        cout << "Enter account number\n? ";
        cin >> accountnumber;

    }
}

Tags: , , ,

C | C++ | OOP | Design Patterns

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Page List