Computer Programming C: UNIT V: File Operations

Types of files: Operations on Sequential, Indexed and Random Files

C Programming

We are going to discuss three types of files mainly, and these types of files are formed depending on the organization of data in the file. (i) Sequential file (ii) Indexed Sequential file (iii) Random Access file

OPERATIONS ON SEQUENTIAL AND RANDOM FILES


Types of files

We are going to discuss three types of files mainly, and these types of files are formed depending on the organization of data in the file.

(i) Sequential file

(ii) Indexed Sequential file

(iii) Random Access file


i. Sequential file

As the name implies that the records are stored and retrieved sequentially i.e., one after another. Sequential file is a data structure which consists of a sequence of records of the same type and size. The records in the file can be read only sequentially. i.e., One after another starting from the beginning of the file.

The primary advantage of a sequential file compared to an any other file is that it can grow or shrink dynamically. The sequential access is the disadvantage. Usually the records in the file are arranged in ascending or descending order of this key field.

To understand the sequential file, lets starts with an example. Consider the example of a tape or rather a cassette where the songs are stored sequentially. Storing data sequentially is the simplest form of file, but a tedious one. Reading data to a file or writing data from it takes a lot of time as the data is not stored. The data is stored on FCFS (First Come First Serve) basis. Taking example where we want to retrieve a record which is unfortunately stored at the last position in the file requires to search the entire file. Hence the time required is very large in this case.

Advantages

• Sequential files are simple to manage.

• Easy to learn and write.

Disadvantages

• Efficiency is less.

• Time required to retrieve any record is more, as the entire file is searched.

So owing to these drawbacks, let us start with other file which will overcome these drawbacks.

Example: Program for a sequential file organization, the input data is string of songs and the play function plays (actually displays) the desired song.

    /* Program for a sequential file organization, the input data is string of songs and the play function plays the desired song */

#include <stdio.h>

#include <conio.h>

#include<stdlib.h> /*standard library function header file*/

#include <string.h> /*add(), play (), display() are the functions */

void add();

void play();

void display();

struct tape /*tape is a structure with integer sno and character string*/

{

      int sno;

      char song[20];

};

struct tape t;

FILE *fp = NULL; /* file_pointer */

void main()

{

int ch;

char ans = 'y';

while (ans == 'y' || ans == 'Y')

{

      printf("MENU \n");

      printf(" 1 ADD SONG \n");

      printf(" 2 DISPLAY SONG \n");

      printf(" 3 PLAY SONG \n");

      printf(" 4 EXIT \n");

      printf("Enter your choice :");

      scanf("%d", &ch);

      switch (ch)

      {

      case 1:

            add(); /* function call */

            break;

      case 2:

            display(); /* function call */

            break;

      case 3:

            play(); /* function call */

            break;

      case 4:

            exit(0);

      break;

      default:

      exit(0);

} /* switch */

printf("\n \t continue to menu(y/n)...");

scanf("%c",&ans);

} /* while */

/* main */

void add()

{

char next = 'y';

fp=fopen("music.dat", "a");   /*fopen function creates a new file*/

if(fp== NULL)

{

      printf("file open error ");

      exit(0);

} /* if */

while (next == 'y' || next == 'Y')

{

      printf("Enter song No :\t");

      scanf("%d", &t. sno);

      printf("Enter song name:\t");

      gets (t.song);

      fwrite(&t, sizeof(t),1,fp);   /* fwrite function writes data to the file! */

      printf("Add more songs (y/n)....");

      scanf("%c", &next);

} /* while */

fclose(fp);

} /* add()* */

void display()

{

fp = fopen("music.dat", "r");

if(fp== NULL)

{

      printf("file open error");

      exit(0);

} /* if */

while (fread(&t, sizeof(t), 1,fp))

{

      printf("\n \t");

      printf("%d\t%s", &t.sno, t.song);

} /* while */

fclose(fp);

} /* display */

void play()

{

char name[20]; /* name is a character array */

int flag = 0;

printf("Enter song name to play :");

scanf("%s", name);

fp = fopen("music.dat", "r");

if(fp == NULL)

{

      printf("file open error");

      exit(0);

} /* if */

while (fread(&t, sizeof(t),1,fp))

{

if(strcmp(t.song, name)==0)

{

      flag = 1;

      break;

} /* if */

} /* while */

if(flag == 1)

{

      printf("\n playing song……\n");

      printf("song No.... %d\n", t.sno);

      printf("song name.... %s", t.song);

} /* if */

else

      printf("Not found");

fclose(fp); /* file close function closes a file*/

} /* play() */

OUTPUT

Menu

1 Add song

2 DISPLAY song

3 Play song

4 EXIT

Enter your choice :1

Enter song No: 1

Enter song name : o podu

Add more songs (y/n)....

      continue to menu(y/n)...y

Menu

1 Add song

2. DISPLAY song

3 Play song

4 EXIT

Enter your choice : 1

Enter song No : 2

Enter song name: raja

Add more songs (y/n)....

      continue to menu(y/n)...y

Menu

1 Add song

2 DISPLAY song

3 Play song

4 EXIT

Enter your choice choice :1

Enter song No : 3

Enter song name : kanne

Add more songs (y/n)....

      continue to menu(y/n)...

Menu

1 Add song

2 DISPLAY song

3 Play song

4 EXIT

Enter your choice : 3

Enter song name to play : raja

playing song.....

song No.... 2

song name.... raja

      continue to menu(y/n)... n

 

ii. Indexed Sequential file

Since, we are clear with sequential file, let us now go to another type indexed sequential file format. There are many advantages of using an indexed sequential over sequential. The indexed sequential file maintain two files, they are sequential file and sorted indexed file.

Whatever the data we store it in the sequential file and in the index file we have the primary key of the sequential file along with the offset of that particular record in the sequential file.

To be more precise, lets take the following example. We have to maintain student details, we have

Roll, Name, Age, Marks

To refer to any student, we have another file, which contain

Roll and Offset

This will be in sorted format for the index file. Hence whenever we are referring to any record, first the index file will be searched. From that search the offset is retrieved and the required record can be seek from the sequential file. You will become clearer from the following figure and program.


Example: Program for the indexed sequential file for the student database.

/* Programs for the indexed sequential file for the student database */

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>  /*standard library function header file */

typedef struct student  /*student is a structure with elements*/

{

      int rno;

      char name[20];

      int age;

      int marks;

}ss;

typedef struct index /* index is a structure with integer *

{

      int irno;

      long offset;

      int flag;

}is;

FILE *ptr= NULL;   /* file pointer NULL */

FILE *iptr=NULL;

void main()

{

      int ch;

      int status;

      int rno;

      char opl='y';

      ptr=fopen("std.dat", "wb");

if(ptr == NULL)

{

      printf("file not found");

      getch();

      exit(0);

} /* if */

iptr=fopen("stdl.dat" "wb");

if(iptr== NULL)

{

      printf("file not found");

      getch();

      exit(0);

} /* if */

fclose(ptr); /* file close function closes a file*/

fclose(iptr);

while((op1= 'y') || (op1 = 'Y'))

{

printf("\n1. Add");

printf("\n2. Delete");

printf("\n3. Modify");

printf("\n4. Search");

printf("\n5. Display");

printf("\n6. Exit\n");

printf("Enter your option (1‒6):");

scanf("%d", &ch);

switch(ch)

{

case 1:

      status = ADD_record();

      if(status == 1)

      printf("Record Successfully Added");

      else

            printf("Record could not be Added");

            break;

 

case 2:

      printf("Enter the rollno of the record to delete");

      scanf("%d", &rno);

      status=DELETE_RECORD(rno);

      if(status == 1)

      printf("Record deleted successfully");

else

      printf("Record could not be deleted");

      break;

case 3:

      printf("Enter rollno of the record to modify:");

      scanf("%d", &rno);

      status=MODIFY RECORD(rno);

      if(status == 1)

      printf("Record modified successfully");

      else

      printf("Record could not be modified");

      break;

case 4:

      printf("Enter the rollno to search: ");

      scanf("%d", &rno);

      status = SEARCH_RECORD(rno);

      if(status == 1)

      printf("Record found");

      else

      printf("Record not found");

      getch();

      break;

case 5:

      DISPLAY ALL_RECORD();

      break;

case 6:

      exit(0);

} /* switch */

fflush(stdin); /* flush function is used to flush a file */

printf("\nDo You want to continue (Y/N): ");

scanf("%c", &op1);

if((op1 == 'n') || (op1== 'N'))

break;

} /* while */

} /* main */

int ADD RECORD()

{

ss stud;

is ind;

long offset;

ptr=fopen("std.dat", "rb+ ");

if(ptr== NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

while(fread(& stud, sizeof(stud), 1,ptr));

offset=ftell(ptr); /*ftell() is used to specify the position */

printf("Rollno: ");

scanf("%d", &stud. rno);

printf("Name of the student: ");

scanf("%s", & stud.name);

printf("Age: ");

scanf("%d", &stud. age);

printf("Marks: ");

scanf("%d", & stud.marks);

fwrite(&stud, sizeof(stud), 1,ptr); /*fwrite writes data to file*/

fclose(ptr); /* fclose closes a file associated with pointer*/

iptr=fopen("std1.dat", "ab+");

if(iptr== NULL)

       printf("File not opened");

      return ‒1;

} /* if */

ind.irno stud.rno;

ind.offset offset;

ind.flag = 1;

fwrite(&ind, sizeof(ind), 1,iptr);

fclose(iptr);

SORT FILE();

return 1;

} /* ADD RECORD() */

int DELETE RECORD(int_rno)

{

     is ind;

     int flag=0;

     iptr=fopen("std1.dat", "rb + ");

if(iptr== NULL)

{

      printf("File not opened");

      return ‒1;

} /* if */

while (fread(&ind, sizeof(is),1,iptr));

{

      if(ind.irno ==rno)

     {

         flag = 1;

     } /* if */

} /* while */

if(flag==1)

{

ind.flag = ‒1;

fseek(iptr, ‒(long) sizeof(is), SEEK_CUR);

fwrite(&ind, sizeof(is),1,iptr);

fclose(iptr);

return 1;

} /* if */

fclose(iptr);

return ‒1;

} /* DELETE_RECORD() */

int MODIFY RECORD (int rno).

{

is ind;

ss stud;

int flag=0;

iptr=fopen("std1.dat", "rb+ ");

if(iptr== NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

while (fread(&ind, sizeof(is), 1,iptr))

if(ind.irno == rno)

{

       flag=1;

       break;

} /* if */

} /* while */

fclose(iptr); /* file close */

if(flag == 1)

{

         ptr=fopen("std.dat", "rb+ ");   /* file open */

if(ptr == NULL)

{

       printf("File not opened");

       return ‒1;

} /* if */

fseek(ptr, ind.offset, SEEK_SET); /*fseek() position pointer*/

fread(&stud, sizeof(stud), 1,ptr); /*fread() used to read data*/

printf("Enter Name:");

scanf("%s", stud. name);

printf("Age:");

scanf("%d", &stud. age);

printf("Marks: ");

scanf("%d", & stud. marks);

fseek(ptr, (long) sizeof(stud), SEEK CUR);

fwrite(& stud, sizeof(stud), 1,ptr); /* file write */

fclose(ptr); /* file close */

return 1;

} /* if */

return ‒1;

}  /* MODIFY RECORD */

int SEARCH_RECORD(int rno)

{

is ind;

ss stud;

iptr=fopen("stdl.dat", "rb+ ");

if(iptr== NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

while (fread(&ind, sizeof(is), 1,iptr))

{

if(ind.irno ==rno && ind. flag==1)

{

     fclose(iptr);

     return 1;

} /* if */

} /* while */

fclose(iptr); /* file close*/

return ‒1;

} /* SEARCH_RECORD() */

int DISPLAY ALL RECORD()

{

is ind;

ss stud;

iptr=fopen("std1.dat", "rb + ");

if(iptr== NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

ptr=fopen("std.dat", "rb+ ");

if(ptr== NULL)

{

     printf("file not opened");

     return ‒1;

} /* if */

while(fread(&ind, sizeof(is), 1,iptr)) /* file read */

{

if(ind.flag == 1)

{

     fseek(ptr, ind. offset, SEEK_SET);

     fread(&stud, sizeof(stud), 1, ptr); /* file read */

     printf("\n\n Rollno %d", stud.rno);

     printf("\n Name : %s", stud.name);

     printf("\n Age : %d", stud.age);

     printf("\n Marks: %d", stud.marks);

} /* if */

} /* while */

fclose(iptr); /* file close */

fclose(ptr); /* file close */

return 1;

} /* DISPLAY ALL RECORD() */

int SORT FILE()

{

int size;

int i,j,flag=0;

is ind, ind_temp;

ss stud;

iptr=fopen("stdl.dat", "rb + ");

if(iptr == NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

ptr=fopen("std.dat", "rb+ ");

if(ptr= = NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

size=0;

while(fread(&ind, sizeof(is),1,iptr))

size++;

fclose(iptr);

iptr=fopen("std.dat", "rb+");

if(iptr== NULL)

{

     printf("File not opened");

     return ‒1;

} /* if */

for(i=0;i< size;i++)

{

     flag = 0;

     for(j=0;j< size‒(i+1);j++)

     {

     fseek(iptr,j* sizeof(is), SEEK__set);

     fread(&ind, sizeof(is), 1,iptr);

     fread(&ind_temp, sizeof(is), 2, iptr);

          if(ind.irno > ind_temp. irno)

          {

               fseek(ptr,j*sizeof(is), SEEK_SET);

               fwrite(&ind_temp, sizeof(is),1,iptr);

               fseek(iptr, (j+1)*sizeof(is), SEEK_SET);

               fwrite(&ind, sizeof(is),1,iptr);

               flag=1;

          } /*  if  */

     if (flag === 0)

          break;

} /* for */

fclose(iptr);

return 1;

} /* for */

} /* SORT FILE() */

OUTPUT

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1‒6):1

Rollno:01

Name of the student: muni

Age:25

Marks:78

Record Successfully Added

Do You want to continue (Y/N): y

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1‒6):1

Rollno:02

Name of the student: venkat

Age:24

Marks:67

Record Successfully Added

Do You want to continue (Y/N): y

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1‒6):1

Rollno:03

Name of the student: shankar

Age:30

Marks:79

Record Successfully Added

Do You want to continue(Y/N): y

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1‒6):2

Enter the rollno of the record to delete 02

Record could not be deleted

Do you want to continue(Y/N): y

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1‒6):3

Enter rollno of the record to modify: 3

Enter Name: shankar

Age:30

Marks:89

Record modified successfully

Do You want to continue (Y/N): y

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1‒6):5

Rollno : 1

Name: muni

Age : 25

Marks : 78

Rollno: 2

Name: mahi

Age : 24

Marks : 67

Rollno: 3

Name: suma

Age : 30

Marks : 89

Do You want to continue (Y/N):6

EXPLANATION: The structure student and index are declared as global structure. The main function opens the file std.dat. If the file is NULL. Then prints file not found. Then open the file std1.dat if the file is NULL then prints file not found and close the both file pointer. The while loop reads the value of option ch and executes to switch case statement depends upon the user entered value. The ADD_RECORD() function opens the file std.dat and reads stud.no, stud.name, stud.age, stud.marks, and executes the body of the function. The function DELETE_RECORD() executes the body of function and while loop, if statements are executed in the body. This function is used for Delete the items. The MODIFY_RECORD() function executes the body and reads stud.name, stud.age, stud.marks, SEARCH_RECORD() function executes the body and close the file iptr. The DISPLAY_ALL_RECORD() function prints the stud.rno, stud.name, stud.age, stud.marks and closed the file pointer iptr. The SORT_FILE() function used the if statement and for loop structure reads and writes the file and finally used the file prints iptr and terminates the program.


iii. Random Access Files

In case of sequential file or indexed sequential file we are writing records to the sequential file as they come. But in case of direct access files, we write the record to a particular position. Since we are deciding the position of the particular record, there is some relation between the key (which is used to access the record) using which we are deciding the position of the record. Hence using the relation between the key and record number, we can determine if a given record is present in the file or not.

 

Computer Programming C: UNIT V: File Operations : Tag: Computer Science : C Programming - Types of files: Operations on Sequential, Indexed and Random Files


Computer Programming C: UNIT V: File Operations



Under Subject


Computer Programming C

CS25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation



Related Subjects


English Essentials I

EN25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


தமிழர் மரபு - Heritage of Tamils

UC25H01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Applied Calculus

MA25C01 Maths 1 M1 - 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Applied Physics I

PH25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Applied Chemistry I

CY25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Makerspace

ME25C04 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Computer Programming C

CS25C01 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Computer Programming Python

CS25C02 1st Semester | 2025 Regulation | 1st Semester 2025 Regulation


Fundamentals of Electrical and Electronics Engineering

EE25C03 1st Semester EEE Depart | 2025 Regulation | 1st Semester 2025 Regulation


Introduction to Mechanical Engineering

ME25C03 1st Semester Mechanical Dept | 2025 Regulation | 1st Semester 2025 Regulation


Introduction to Civil Engineering

CE25C01 1st Semester Civil, Agri Departments | 2025 Regulation | 1st Semester 2025 Regulation


Essentials of Computing

CS25C03 1st Semester - AIDS, CSE, CSE(CY), IT Department | 2025 Regulation | 1st Semester 2025 Regulation


Applied Physics I Laboratory

PH25C01 1st Semester practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Applied Chemistry I Laboratory

CY25C01 1st Semester practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Computer Programming C Laboratory

CS25C01 1st Semester EEE, ECE, CSE, CSE(CY), AIDS, IT practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Computer Programming Python Laboratory

CS25C02 1st Semester practical Laboratory Manual | 2025 Regulation | 1st Semester Laboratory 2025 Regulation


Engineering Drawing

ME25C01 EEE, Mech, Agri, EEE Depts | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electronics and Electrical Engineering

EE25C04 1st Semester ECE Dept | 2025 Regulation | 1st Semester 2025 Regulation


Essentials of Computing - Laboratory

CS25C03 1st Semester AIDS, CSE, CSE(CY), IT Depts | practical Laboratory Manual | 2025 Regulation | 1st Semester 2025 Regulation