Write a program that first appends the customer records in a data file and displays the number of customer records as well as the contents from the file.

Solution to this problem is shown below. Which is written in OOP concept.

    #include<iostream>
    // for file operations
    #include<fstream>
    #include<cstring>

    using namespace std;
    class Customer{
        private:
            char name[30];
            int age;
        public:
            void read_data(){
                cout<<"Enter Name:"<<endl;
                // this does not accept space contained string
                cin>>name;
                cout<<"Enter Age:"<<endl;
                cin>>age;
            }
            void write_to_file(){
                Customer cu;
                ofstream file("customer_record.txt",ios::app);
                cu.read_data();
                file.write(reinterpret_cast<char *>(&cu), sizeof(cu));
            }
            void read_from_file(){
                Customer cu;
                ifstream file("customer_record.txt");
                while(!file.eof()){
                    if (file.read(reinterpret_cast<char*>(&cu), sizeof(cu))){
                        cu.show_data();
                    }
                }
            }
            void show_data(){
                cout<<"Name : "<<name<<endl;
                cout<<"Age : "<<age<<endl;
            }
            void show_all_record(){
                Customer cu;
                ifstream file("customer_record.txt");
                cout<<"#### All Customer records are ####"<<endl;
                while (file.read(reinterpret_cast<char *>(&cu), sizeof(cu)))
                {
                    cu.show_data();
                }
            }
            int get_total_record(){
                Customer cu;
                long file_size;
                ifstream file("customer_record.txt");
                file.seekg(0, ios::end);
                file_size = file.tellg();
                return file_size/sizeof(cu);
            }
    };


    int main(){
        Customer cu;
        cout<<"Enter Customer info:"<<endl;
        cu.write_to_file();
        cout<<"Total Records:"<<cu.get_total_record()<<endl;
        cu.show_all_record();
        return 0;
    }

Sample Output of the program is shown below, however the out that you get may differ:

Enter Customer info:
Enter Name:
Rambo
Enter Age:
66
Total Records:11
#### All Customer records are ####
Name : sadhu
Age : 23
Name : rahi
Age : 34
Name : dohi
Age : 45
Name : bri
Age : 34
Name : hari
Age : 23
Name : Dino
Age : 22
Name : Zhang
Age : 34
Name : Hary
Age : 22
Name : Roman
Age : 55
Name : Chris
Age : 44
Name : Rambo
Age : 66

Process returned 0 (0x0)   execution time : 5.084 s
Press any key to continue.