Skip to main content

Sequential File Handling using CPP to store data of studenets

 Problem Statement:- Department maintains student information. The file contains the roll number, name, division and address. Allow user to add, and delete information of student. Display information about a particular student. If the record of the student does not exist an appropriate message is displayed. If it is, then the system displays the student details. Use the sequential file to maintain the data.

Note:- Scroll horizontally to see the full line of code.

#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
using namespace std;
const int MAX = 20;
class Student
{
    int rollno;
    char name[20], city[30];
    int div;
    int year;

public:
    Student()
    {
        strcpy(name, "");
        strcpy(city, "");
        rollno = year = div = 0;
    }
    Student(int rollno, char name[MAX], int year, int div, char city[MAX])
    {
        strcpy(this->name, name);
        strcpy(this->city, city);
        this->rollno = rollno;
        this->year = year;
        this->div = div;
    }
    int getRollNo()
    {
        return rollno;
    }
    void displayRecord()
    {
        cout << endl
             << setw(5) << rollno << setw(10) << name << setw(10)
             << year << setw(10) << div << setw(15) << city;
    }
};
//==========File Operations ===========
class FileOperations
{
    fstream file;

public:
    FileOperations(char *filename)
    {
        file.open(filename, ios::in | ios::out | ios::ate | ios::binary);
    }
    void insertRecord(int rollno, char name[MAX], int year, int div,
                      char city[MAX])
    {
        Student s1(rollno, name, year, div, city);
        file.seekp(0, ios::end);
        file.write((char *)&s1, sizeof(s1));
        file.clear();
    }
    void displayAll()
    {
        Student s1;
        file.seekg(0, ios::beg);
        while (file.read((char *)&s1, sizeof(s1)))
        {
            s1.displayRecord();
        }
        cout << endl;
        file.clear();
    }
    void searchRecord(int rollNo)
    {
        Student s1;
        file.seekg(0, ios::beg);
        bool flag = false;
        while (file.read((char *)&s1, sizeof(s1)))
        {
            if (s1.getRollNo() == rollNo)
            {
                s1.displayRecord();
                flag = true;
                break;
            }
        }
        cout << endl;
        if (flag == false)
        {
            cout << "\nRecord of " << rollNo << "is not present." << endl;
        }
        file.clear();
    }
    void deleteRecord(int rollno)
    {
        ofstream outFile("new.txt", ios::binary);
        file.seekg(0, ios::beg);
        bool flag = false;
        Student s1;
        while (file.read((char *)&s1, sizeof(s1)))
        {
            if (s1.getRollNo() == rollno)
            {
                flag = true;
                continue;
            }
            outFile.write((char *)&s1, sizeof(s1));
        }
        if (!flag)
        {
            cout << "\nRecord of " << rollno << "    is not present.";
        }
        file.close();
        outFile.close();
        remove("student.txt");
        rename("new.txt", "student.txt");
        file.open("student.txt", ios::in | ios::out | ios::ate | ios::binary);
        cout << "Record Deleted Successfully!!!" << endl;
    }
    ~FileOperations()
    {
        file.close();
        cout << "File Closed.";
    }
};
int main()
{
    ofstream newFile("student.txt", ios::app | ios::binary);
    newFile.close();
    FileOperations file((char *)"student.txt");
    int rollNo, year, choice, div;
    char name[MAX], address[MAX];
    char cont = 'y';
    while (cont == 'y')
    {
        cout << "<--------Menu-------->" << endl;
        cout << "1. Add New Records" << endl;
        cout << "2. Display All Records" << endl;
        cout << "3. Search the Record" << endl;
        cout << "4. Delete a Record" << endl;
        cout << "5. Exit" << endl;
        ;
        cout << "Enter choice : ";
        cin >> choice;
        switch (choice)
        {
        case 1:
            int n;
            cout << "Enter the number of records: ";
            cin >> n;
            for (int i = 0; i < n; i++)
            {
                cout << "\n -----------------------------------------\n";
                cout << "Enter the details of student: " << endl;
                cout << "Name: ";
                cin >> name;
                cout << "Division: ";
                cin >> div;
                cout << "Roll No. : ";
                cin >> rollNo;
                cout << "Year: ";
                cin >> year;
                cout << "Address: ";
                cin >> address;
                file.insertRecord(rollNo, name, year, div, address);
            }
            cout << "Records Inserted Successfully!!!" << endl;
            break;
        case 2:
            cout << endl
                 << setw(5) << "ROLL" << setw(10) << "NAME" << setw(10)
                 << "YEAR" << setw(10) << "DIV" << setw(15) << "CITY";
            file.displayAll();
            break;
        case 3:
            cout << "Enter Roll no. to be Searched: ";
            cin >> rollNo;
            cout << endl
                 << setw(5) << "ROLL" << setw(10) << "NAME" << setw(10)
                 << "YEAR" << setw(10) << "DIV" << setw(15) << "CITY";
            file.searchRecord(rollNo);
            break;
        case 4:
            cout << "Enter Roll no. to be deleted: ";
            cin >> rollNo;
            file.deleteRecord(rollNo);
            break;
        default:
            cout << "Invalid Choice!!!" << endl;
            break;
        }
        cout << "Do you want to continue ? (y/n) : ";
        cin >> cont;
    }
    cout << "Program Ended Successfully!!!" << endl;
    return 0;
}

Comments

Popular posts from this blog

SET THEORY USING LIST IN PYTHON

Problem Statement :- In second-year computer engineering class, group A student's play cricket, group B students play badminton and group C students play football.  Write a Python program using functions to compute the following:-     a) List of students who play both cricket and badminton     b) List of students who play either cricket or badminton or both     c) Number of students who play neither cricket nor badminton     d) Number of students who play cricket and football but not badminton. (Note- While realizing the group, duplicate entries should be avoided, Do not use SET built-in functions) Note :- Scroll horizontally to see the full line of code. def   Addelem ( A ,  a ):      for   i   in   range  ( a ):          elem = input ( "Enter the name of student:" )          if ( elem   ...

Uninstalling AnyDesk from Ubuntu: A Step-by-Step Guide

If you're an Ubuntu user looking to remove AnyDesk from your system and reclaim valuable space, this straightforward guide will walk you through the uninstallation process with easy-to-follow steps. Step 1: Launch the Terminal To initiate the uninstallation process, open the Terminal on your Ubuntu system by simultaneously pressing "Ctrl + Alt + T." Step 2: Verify AnyDesk Installation Confirm that AnyDesk is installed on your system by typing the following command in the Terminal and pressing "Enter": dpkg -l | grep anydesk The relevant information will be displayed if AnyDesk is installed. Step 3: Uninstall AnyDesk Remove AnyDesk from your Ubuntu system using the following command in the Terminal: sudo apt-get remove anydesk Enter your user password when prompted (characters won't be visible as you type) and press "Enter" to authorize the uninstallation. Step 4: Confirm Unins...

Implementations of Search Algorithms using Python | Linear Sequential Search | Sentinel Sequential Search | Binary Search | Fibonacci Search

  Problem Statement:-  a) Write a Python program to store roll numbers of student in array who attended training program in random order. Write function for searching whether particular student attended training program or not, using Linear search and Sentinel search. b) Write a Python program to store roll numbers of students array who attended training program in sorted order. Write function for searching whether particular student attended training program or not, using Binary search and Fibonacci search. Note:-  Scroll horizontally to see the full line of code. def linear_search ( a , target ):     for i in range ( len ( a )):         if ( a [ i ]== target ):             print ( "Roll no." , target , "is present at index" , i )             break     else :         print ( "Roll no." , target , "not found in list" ) def binary_search ( a , targ...

C++ Program for storing Appointments Schedule for day using Linked list | Display Free Slots | Book Appointment | Cancel Appointment | Sort Appointments

  Problem Statement: Write C++ program for storing appointment schedule for day. Appointments are booked randomly using linked list. Set start and end time and min and max duration for visit slot. Write Functions for-     A) Display free slots     B) Book appointments     C) Sort list based on time     D) Cancel appointment ( check validity, time bounds, availability )     E) Sort list base on time using pointer manipulation. Note: Scroll Horizontally to see the full line of code. #include < iostream > using namespace std ; class slot { public :     int startTime , endTime , min , max ;     bool status ;     slot * next ;     slot ( int start , int end , int min , int max )     {         startTime = start ;         endTime = end ;         this -> min = min ;         this ->...

Complete Guide: Uninstalling Steam from Ubuntu - Step-by-Step

Steam is widely favored among gamers for its seamless game distribution and vibrant community engagement. However, excessive game installations can burden your PC, leading to sluggish performance and potential system crashes. If you're facing such issues, a thorough uninstallation of Steam from your Ubuntu system might be the solution. Simply removing Steam using standard methods may leave residual files and directories on your device, potentially causing lingering issues. This comprehensive guide will walk you through the process of completely removing Steam from your Ubuntu system. Steps to Fully Uninstall Steam from Ubuntu: Before proceeding, ensure to back up any important data as uninstalling Steam will also remove all associated games, DLCs, and saved data. Follow these steps to uninstall Steam from Ubuntu: Step 1: Open the terminal by right-clicking or pressing “ctrl...