Thursday, 9 March 2017

C File program to Add and Retrive an Employee record

 -------------------------1)Emp.c to create emp.rec file
#include <stdio.h>

void main()
{
    FILE *fptr;
    char name[20];
    int age;
    float salary;

    fptr = fopen ("emp.rec", "w"); /* open for writing*/

    if (fptr == NULL)
    {
        printf("File does not exists \n");
        return;
    }
    printf("Enter the name \n");
    scanf("%s", name);
    fprintf(fptr, "Name    = %s\n", name);
    printf("Enter the age \n");
    scanf("%d", &age);
    fprintf(fptr, "Age     = %d\n", age);
    printf("Enter the salary \n");
    scanf("%f", &salary);
    fprintf(fptr, "Salary  = %.2f\n", salary);
    fclose(fptr);
}
 ----------------------------2) read.c to read file content from emp.rec
#include <stdio.h>

#include <stdlib.h>

 void main()

{

    FILE *fptr;

    char filename[15];

    char ch;


    printf("Enter the filename to be opened \n");

    scanf("%s", filename);

    /*  open the file for reading */

    fptr = fopen(filename, "r");

    if (fptr == NULL)

    {

        printf("Cannot open file \n");

        exit(0);

    }

    ch = fgetc(fptr);

    while (ch != EOF)

    {

        printf ("%c", ch);

        ch = fgetc(fptr);

    }

    fclose(fptr);

}