Saturday, August 27, 2011

Mini project Employee record system using C

The employee record system is very simple and for very beginner mini project. It is based one the menu-driven program for elementary database management. It employ all the basic technique of file handling in C. It consists of following features
  • Writing the data in binary file
  • Reading the data from binary file
  • Modify the record
  • Delete the record
This project is a learning milestone for beginner who want to step into the database management project in C.
Source Code
/**
*  A menu-driven program for elementary database management
*  @author: Bibek Subedi
*  @language: C
*  This program uses file handling in Binary mode
*/

/// List of library functions
#include <stdio.h> ///for input output functions like printf, scanf
#include <stdlib.h>
#include <conio.h>
#include <windows.h> ///for windows related functions (not important)
#include <string.h>  ///string operations

/** List of Global Variable */
COORD coord = {0,0}; /// top-left corner of window

/**
    function : gotoxy
    @param input: x and y coordinates
    @param output: moves the cursor in specified position of console
*/
void gotoxy(int x,int y){
    coord.X = x; coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}

/** Main function started */

int main(){
    FILE *fp, *ft; /// file pointers
    char another, choice;

    /** structure that represent a employee */
    struct emp{
        char name[40]; ///name of employee
        int age; /// age of employee
        float bs; /// basic salary of employee
    };

    struct emp e; /// structure variable creation

    char empname[40]; /// string to store name of the employee

    long int recsize; /// size of each record of employee

    /** open the file in binary read and write mode
    * if the file EMP.DAT already exists then it open that file in read write mode
    * if the file doesn't exit it simply create a new copy
    */
    fp = fopen("EMP.DAT","rb+");
    if(fp == NULL){
        fp = fopen("EMP.DAT","wb+");
        if(fp == NULL){
            printf("Connot open file");
            exit(1);
        }
    }

    /// sizeo of each record i.e. size of structure variable e
    recsize = sizeof(e);

    /// infinite loop continues untile the break statement encounter
    while(1){
        system("cls"); ///clear the console window
        gotoxy(30,10); /// move the cursor to postion 30, 10 from top-left corner
        printf("1. Add Record"); /// option for add record
        gotoxy(30,12);
        printf("2. List Records"); /// option for showing existing record
        gotoxy(30,14);
        printf("3. Modify Records"); /// option for editing record
        gotoxy(30,16);
        printf("4. Delete Records"); /// option for deleting record
        gotoxy(30,18);
        printf("5. Exit"); /// exit from the program
        gotoxy(30,20);
        printf("Your Choice: "); /// enter the choice 1, 2, 3, 4, 5
        fflush(stdin); /// flush the input buffer
        choice  = getche(); /// get the input from keyboard
        switch(choice){
            case '1':  /// if user press 1
                system("cls");
                fseek(fp,0,SEEK_END); /// search the file and move cursor to end of the file
                                        /// here 0 indicates moving 0 distance from the end of the file

                another = 'y';
                while(another == 'y'){ /// if user want to add another record
                    printf("\nEnter name: ");
                    scanf("%s",e.name);
                    printf("\nEnter age: ");
                    scanf("%d", &e.age);
                    printf("\nEnter basic salary: ");
                    scanf("%f", &e.bs);

                    fwrite(&e,recsize,1,fp); /// write the record in the file

                    printf("\nAdd another record(y/n) ");
                    fflush(stdin);
                    another = getche();
                }
                break;
            case '2':
                system("cls");
                rewind(fp); ///this moves file cursor to start of the file
                while(fread(&e,recsize,1,fp)==1){ /// read the file and fetch the record one record per fetch
                    printf("\n%s %d %.2f",e.name,e.age,e.bs); /// print the name, age and basic salary
                }
                getch();
                break;

            case '3':  /// if user press 3 then do editing existing record
                system("cls");
                another = 'y';
                while(another == 'y'){
                    printf("Enter the employee name to modify: ");
                    scanf("%s", empname);
                    rewind(fp);
                    while(fread(&e,recsize,1,fp)==1){ /// fetch all record from file
                        if(strcmp(e.name,empname) == 0){ ///if entered name matches with that in file
                            printf("\nEnter new name,age and bs: ");
                            scanf("%s%d%f",e.name,&e.age,&e.bs);
                            fseek(fp,-recsize,SEEK_CUR); /// move the cursor 1 step back from current position
                            fwrite(&e,recsize,1,fp); /// override the record
                            break;
                        }
                    }
                    printf("\nModify another record(y/n)");
                    fflush(stdin);
                    another = getche();
                }
                break;
            case '4':
                system("cls");
                another = 'y';
                while(another == 'y'){
                    printf("\nEnter name of employee to delete: ");
                    scanf("%s",empname);
                    ft = fopen("Temp.dat","wb");  /// create a intermediate file for temporary storage
                    rewind(fp); /// move record to starting of file
                    while(fread(&e,recsize,1,fp) == 1){ /// read all records from file
                        if(strcmp(e.name,empname) != 0){ /// if the entered record match
                            fwrite(&e,recsize,1,ft); /// move all records except the one that is to be deleted to temp file
                        }
                    }
                    fclose(fp);
                    fclose(ft);
                    remove("EMP.DAT"); /// remove the orginal file
                    rename("Temp.dat","EMP.DAT"); /// rename the temp file to original file name
                    fp = fopen("EMP.DAT", "rb+");
                    printf("Delete another record(y/n)");
                    fflush(stdin);
                    another = getche();
                }
                break;
            case '5':
                fclose(fp);  /// close the file
                exit(0); /// exit from the program
        }
    }
    return 0;
}

Output

employee

11 comments:

  1. we need to download "windows.h" for code support

    please provide us the same.

    ReplyDelete
    Replies
    1. I think you tried it on Turbo C which doesn't support windows.h. Best way is to use Code::Blocks IDE having GCC compiler

      Delete
  2. Hey can any one help me to make project on "Review Management System"..please i dont have any idea how to make it give me any code or idea how to do it...

    ReplyDelete
  3. sir i want school managment system project in c language
    my id is humayunejaz64@gmail.com
    kindly send me this project as soon as possible

    ReplyDelete
  4. MAY I KNOW THE FLOWCHART FOR THIS PROJECT ??

    ReplyDelete
  5. // Do not change, delete or rename any thing in the following code
    // Complete this program by creating the missing functions
    // and providing and menu driven interface
    #include pl give me the correct ans whats wrong in this programe

    #include
    #include
    using namespace std;

    struct EmpSal{
    int empId;
    char name[50];
    int basic;
    double commRate;
    };


    int searchEmpId(EmpSal emp[], int id);
    void printEmp(EmpSal emp[], int index);
    void init(EmpSal emp[]);
    //int namefounder(EmpSal []);
    int namefounder(EmpSal emp[], char name[]);

    void main() {
    EmpSal emp[5]; // Struct Array emp is our DB (do not make this array global ... leave it here as it is)
    init(emp); // initialize struct array

    int option = 0;
    do {
    // Here first design and print a menu
    // Then call an appopriate function in each case depending upon the slection made by the user
    int choice;
    cout<<"Please Enter your choice.\n1.Search by id.\n2.Search by name.\n3.Average of basic salary of all employees.\n4.Detail of employee having maximum commision rate.\n5.Earning of an employee.\n6.Print Details.\n7.exit"<>choice;
    switch (choice){
    case 1:{

    // 1- Search Emp by empId
    int id; cout << "Enter the ID you to search : "; cin >> id;
    int index = searchEmpId(emp, id);
    if(index == -1)
    cout << id << " deoes not exist in array." << endl;
    else
    printEmp(emp, index);
    break;}
    case 2:
    {
    char p[50];
    cout<<"Enter the name you want to search : ";
    cin.getline(p,50);


    break;}

    }
    // 2- Search Emp by name (there may be more than one emp having same name)

    // 3- Calculate and Print average of basic salary of all employees

    // 4- Fiand and Print the detail of an employee having maximum commision rate

    // 5- Calculate and print earnings of an employee given its employee id and sales as input ( salary = basic + Commision Rate * (Sales)

    // 6- Print detail of all employees

    // 7- Exit

    } while(option != 7);

    }// end main

    void init(EmpSal emp[]) {
    EmpSal e1 = {101, "Asad Arshad", 5000, 0.10};
    emp[0] = e1;
    EmpSal e2 = {102, "Muddaser Mukhtar", 6000, 0.50};
    emp[1] = e2;
    EmpSal e3 = {103, "Aqib Javed", 7000, 0.10};
    emp[2] = e3;
    EmpSal e4 = {104, "Saqib Sarfraz", 8000, 0.15};
    emp[3] = e4;
    EmpSal e5 = {110, "Asad Arshad", 7000, 0.20};
    emp[4] = e5;
    }
    int namefounder(EmpSal emp[], char name[])// search by name
    {
    int counter=0;
    int flag=0;
    int saver;
    for(int x=0;x<5;x++)
    {
    if(name==emp[x].name)
    {
    saver=x;
    flag=1;
    counter++;
    }

    }
    if(flag==1)
    {
    if(counter==1){return saver;}else
    if(counter>1)
    {int id;
    cout<<"The name "<>id;
    int b=searchEmpId(emp,id);
    if(b== -1)
    {cout<<"The id "< " << endl;
    cout << "Emp ID = " << emp[index].empId << endl;
    cout << "Name = " << emp[index].name << endl;
    cout << "Basic Sal = " << emp[index].basic << endl;
    cout << "Comm Rate = " << emp[index].commRate << endl;
    cout<< "***********************************************" << endl;
    }

    int searchEmpId(EmpSal emp[], int id) {

    int found = 0;
    for(int i=0; i < 5; i++) {
    if( id == emp[i].empId ) {
    return i;
    found = 1;
    break;
    }
    }
    if(found == 0)
    return -1;
    }

    ReplyDelete
  6. Please help me on above progarm i am getting few errors

    #include ///for input output functions like printf, scanf
    #include
    #include
    #include ///for windows related functions (not important)
    #include ///string operations

    /** List of Global Variable */
    COORD coord = {0,0}; /// top-left corner of window

    /**
    function : gotoxy
    @param input: x and y coordinates
    @param output: moves the cursor in specified position of console
    */
    void gotoxy(int x,int y){
    coord.X = x; coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
    }

    /** Main function started */

    int main(){
    FILE *fp, *ft; /// file pointers
    char another, choice;

    /** structure that represent a employee */
    struct emp{
    char name[40]; ///name of employee
    int age; /// age of employee
    float bs; /// basic salary of employee
    };

    struct emp e; /// structure variable creation

    char empname[40]; /// string to store name of the employee

    long int recsize; /// size of each record of employee

    /** open the file in binary read and write mode
    * if the file EMP.DAT already exists then it open that file in read write mode
    * if the file doesn't exit it simply create a new copy
    */
    fp = fopen("EMP.DAT","rb+");
    if(fp == NULL){
    fp = fopen("EMP.DAT","wb+");
    if(fp == NULL){
    printf("Connot open file");
    exit(1);
    }
    }

    /// sizeo of each record i.e. size of structure variable e
    recsize = sizeof(e);

    /// infinite loop continues untile the break statement encounter
    while(1){
    system("cls"); ///clear the console window
    gotoxy(30,10); /// move the cursor to postion 30, 10 from top-left corner
    printf("1. Add Record"); /// option for add record
    gotoxy(30,12);
    printf("2. List Records"); /// option for showing existing record
    gotoxy(30,14);
    printf("3. Modify Records"); /// option for editing record
    gotoxy(30,16);
    printf("4. Delete Records"); /// option for deleting record
    gotoxy(30,18);
    printf("5. Exit"); /// exit from the program
    gotoxy(30,20);
    printf("Your Choice: "); /// enter the choice 1, 2, 3, 4, 5
    fflush(stdin); /// flush the input buffer
    choice = getche(); /// get the input from keyboard
    switch(choice){
    case '1': /// if user press 1
    system("cls");
    fseek(fp,0,SEEK_END); /// search the file and move cursor to end of the file
    /// here 0 indicates moving 0 distance from the end of the file

    another = 'y';
    while(another == 'y'){ /// if user want to add another record
    printf("\nEnter name: ");
    scanf("%s",e.name);
    printf("\nEnter age: ");
    scanf("%d", &e.age);
    printf("\nEnter basic salary: ");
    scanf("%f", &e.bs);

    fwrite(&e,recsize,1,fp); /// write the record in the file

    printf("\nAdd another record(y/n) ");
    fflush(stdin);
    another = getche();
    }
    break;
    case '2':
    system("cls");
    rewind(fp); ///this moves file cursor to start of the file
    while(fread(&e,recsize,1,fp)==1){ /// read the file and fetch the record one record per fetch
    printf("\n%s %d %.2f",e.name,e.age,e.bs); /// print the name, age and basic salary
    }
    getch();
    break;


    ReplyDelete
    Replies
    1. sir you have written in the above code upto case 2!!! what about remaining cases ??? are they ok as you have mention in the top code..?????

      Delete
  7. sir,
    i have some very simple programming doubt in two dimensional character arrays

    here is the program

    # include
    #include
    # include
    void main()
    {
    int i=0;
    char name[3][10];
    printf("\n enter the names \n");
    for(i=0;i<3;i++)
    {
    scanf("%s",name[i]);
    }


    printf("you entered these names\n");
    for(i=0;i<3;i++)
    {
    printf("%s\n",name[i]);
    }
    getch();

    }

    in this program i would like to chk for null character using for statement..how do i do that

    why because suppose..if the size of array is 3X5

    and if I enter any name which is more that 5 characters..I get an error null point termination..

    should I use 2 loops to enter the names and chk for null character

    or with single loop how should I chk

    ReplyDelete
  8. sir I want your help on driving licence management system .I have done the coding part but I am not able to store data my . my teacher has suggested to do file handling in it but I am not able to so


    #include
    #include
    #include
    struct dl
    {
    char name[40];
    char add[100];
    int licno;
    char bg;
    int uid; //unique id number will entered by user like uidai
    };
    struct dl b[100];
    int count=0;
    void addnewdl(struct dl b1[])
    {
    printf("Enter dl no");
    scanf("%d",&b1[count].licno);
    fflush(stdin);
    printf("Enter Name");
    gets(b1[count].name);
    printf("Enter dl holder Address");
    gets(b1[count].add);
    fflush(stdin);
    printf("Enter blood group");
    scanf("%s",b1[count].bg);
    printf("enter udi number");
    scanf("%d",&b1[count].uid);
    }
    void DisplayAll()
    {
    int i;
    for(i=0;i<count;i++)
    {
    printf("\ndl No=%d",b[i].licno);
    printf("\ndl Holder Name=%s",b[i].name);
    printf("\nblood group=%s",b[i].bg);
    printf("\ndl Holder Address=%s",b[i].add);
    }
    }
    void lost()
    {int v;
    printf("enter udi number\n");
    scanf("%d",&b[v].uid);
    printf("complaint reg");
    //printf("\ndl No=%d",b[count].licno);
    //printf("\ndl Holder Name=%s",b[count].name);
    //puts(b[count].name);
    }
    void theft()
    {int x;
    printf("enter udi number\n");
    scanf("%d",&b[x].uid);
    printf("complaint reg");
    //printf("\ndl No=%d",b[x].licno);
    //printf("\ndl Holder Name=%s",b[x].name);
    }
    void main()
    {
    int choice,n;
    while(1)
    {
    printf("\n 1. to apply for new dl");
    printf("\n 2. to display all dl");
    printf("\n 3. register for loss of dl");
    printf("\n 4.register for theft of dl");
    printf("\n 5. to exit");
    printf("\nEnter Your Choice ");
    scanf("%d",&choice);
    switch(choice)
    {
    case 1:
    addnewdl(b);
    count++;
    break;
    case 2:
    DisplayAll();
    break;
    case 3:
    lost();
    break;
    case 4:
    theft();
    break;
    case 5:
    exit(1);
    break;
    }
    }
    getch();
    }

    ReplyDelete
  9. Hey can any one help me to make a c++ project on "employee leave Management System"..please i dont have any idea how to make it plz send me the program as soon as possible on honeygautam499@gmail.com...

    ReplyDelete