C Programming and Data Structures: Unit II: C Programming – Advanced Features

File Handling

Definition, Syntax, Example C programs

• Definition: File is a collection of records. In generalized form, a file of size n has n records in sequence where each record is a collection of one or more fields.

File Handling

Definition: File is a collection of records. In generalized form, a file of size n has n records in sequence where each record is a collection of one or more fields.

• For example:

So with respect to above example we say that the file has 3 records.

To identify each record, a unique key is associated with it. In the above example Roll No. can be thought of as an key. Using this key, we are in position to access the information for that student.

• In C file can be declared using the pointer.

Syntax: FILE *filepointer

Example: FILE *fp;

FILE is a structure which is defined in "stdio.h". Each file we open will have its own FILE structure. The structure contains information like usage of the file, its size, memory location and so on. The fp is a pointer variable which contains the address of the structure FILE.

 

1. Classification of File

• There are two types of files - Text file and Binary file.

• The text files are files in which textual information may be stored with essentially no formatting.

• Binary files in which any type of data (it might be text, image, or audio) encoded in binary form. The binary files contain the binary digits. That means it contains the sequence of 1's and 0's.

Comparison between Text File and Binary File


 

2. File Operations

1. Creating a file / Opening a file :

Syntax filepointer = fopen("filename","mode");

where filename is the name of file you want to create or open

mode can be read - "r"

write - "w"

append - "a"

• Depending on the type of file we want to open/create we use -"rb", "wb", or just "r", "w", "a".

• Using "r" opens the file in read mode. If the file does not exist, it will create a new file, but such a file created is of no use as you cannot write to any file in read mode.

• Using "r+" allows to read from file as well as write to the file.

• Using "w" opens a file in write mode. If the file does not exist, it will create a new file.

•  Using "w+" allows you to write contents to file, read them as well as modify existing contents.

• Using "a" opens the file in append mode. If the file does not exist, then it creates a new file. Opening a file in append mode allows you to append new contents at the end of the file.

• Using "a+" allows to append a file, read existing records, cannot modify existing records.

Example :

fp = fopen("Student.dat","w");

2. Closing the file:

Syntax: fclose(filepointer);

Example :

fclose(fp); /* closes the file pointed by the fp */

3. Setting the pointer to start of file:

Syntax: rewind (filepointer);

Example :

rewind(fp); /* places pointer at the start of the file */

4. Writing a character to file :

Syntax: fputc( character, filepointer);

Example:

Suppose we have

char ch='a';

To write the character to the file, we use

fputc(ch,fp);

Note: If the file is opened in "w" mode, it will overwrite the contents of the entire file and write the only character we want to write. To write it at the end of the file, open the file in "a+" mode.

5. Reading a character from file :

Syntax fgetc( filepointer);

Example :

char ch; /* ch is the character where you are going to get the char from file*/ ch= fgetc(fp);

6. Writing string to file :

Syntax fputs(string, filepointer);

Example :

Suppose you have a string

char s[]="abcd";

then we write as

fputs(s,fp);

The above operation writes the string "abcd" to the file pointed by fp.

7. Reading string from file :

Syntax fgets(stringaddress, length, filepointer);

Example :

char s[80]; /* declared a string into which we want to read the string from file */esolat fgets(s,79,fp); /* Will read the 78, (79-1) characters of string from file into s */

8. Writing of characters, strings, integers,floats to file :

Syntax :

fprintf(filepointer, "format string", list of variables);

We are already aware of the printf function. fprintf has the same arguments as that of printf, addition to which filepointer is added. The variables included in the fprintf are written to the file. But how can we write the data without knowing their values, so we need to have a scanf function before it and then can write the data to file. You will understand this better by following example.

'C' Program

/**************************************************************

Program for introducing the file primitives such as fopen,fclose, fprintf.

**************************************************************/

#include<stdio.h>

/*

The main Function

Input:none

Output:none

Called By:O.S.

*/

main()

{

FILE *fp;

int rno;

char name[20];

clrscr();

fp = fopen("Student.dat", "w");

if(fp== NULL)

{

printf("File opening error");

 exit(1);

 }

printf("Enter the rollno and name:");

 scanf("%d %s", &rno,&name);/* asking user to enter data */

fprintf(fp,"%d %s", &rno,&name); /* writing data to file */

fclose(fp);

getch();

 return;

}

/************End Of Program************/

Output

Enter the rollno and name:

1

aaa

student.dat

1 aaa

9. Reading of variables from file:

Syntax:

fscanf(filepointer, "format string",list of addresses of variables);

Having similar arguments as that of the fprintf statement, the fscanf reads the contents of the file into the variables specified.

Example :

fscanf(fp,"%d %s", &rno,&name);

printf("Read data is: %d %s",rno,name);

Note: The fprintf and fscanf statements are useful only when the data we want to enter is less, or rather they have disadvantage that when the number of variables increase, writing them or reading them becomes clumsy.

10. Writing contents to file through structure :

Syntax: fwrite(pointer to struct, size of struct,no.of data items, filepointer);

/************************************************************

Program for file primitives such as fopen, fwrite. This program writes the string to the file.

**************************************************************/

#include<stdio.h>

#define MAX 20

struct stud /* structure declaration */

{

int rno;

char name[MAX];

};

main() {

struct stud s;

FILE *fp;

clrscr();

s.rno=1;

/* fill the structure contents*/

strcpy(s.name,"Sachin");

fp = fopen("Student.dat", "w");

if(fp== NULL)

{

printf("File opening error");

 exit(1);

}

fwrite(&s,sizeof(s),1,fp); /* write the structure contents to file*/

fclose(fp);

return;

}

Output

student.dat

Sachin 0 =+ 2

Thus we can see from the output of the program that fwrite writes the data in the file in binary mode.

11. Reading contents of file through structure :

Syntax:- fread(pointer to struct,size of struct,no.of data items, filepointer);

Example :

To read the contents written in file we can have:-

fread(&s,sizeof(s),1,fp);

Note: Prior to this statement it is necessary that the pointer is located at the proper position from where we want to read the file. Here you can use the rewind(filepointer) function.

An fread or fwrite function moves the pointer to the beginning of the next record in that file.

12. Moving the pointer from one record to another :

Syntax: fseek(filepointer, offset, whence);

where

offset is difference in bytes between offset and whence position.

whence can be:

1) SEEK_SET move the pointer with reference to beginning of the file.

 2) SEEK_CUR move the pointer with reference to its current position in file.

 3) SEEK_END move the pointer from end of file.

Example :

Let us take the example where we have written a record in file. Suppose we want to read that record, we have two options:

1) To use rewind function.

2) To use fseek.

We can use fseek in following fashion :

prior to the fclose(fp), we can have

fseek(fp,-sizeof(s), SEEK_CUR);

This will place the pointer to the beginning of the record we have currently written. Then we can make use of fread(...) to read that record again.

/******************************************************

Use of fseek for positioning the pointers in file

***********************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

struct record

{

int a;

};

void main()

int i,j;

FILE *fp;

struct record r;

clrscr();

/* create the file of 10 records */

fp=fopen("input.dat","w");

for (i=1;i<=10; i++)

{

r.a=i;

fwrite(&r,sizeof(struct record),1,fp);

}

fclose(fp);

printf("\n Reading First Record\n");

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

fseek(fp,OL,SEEK_SET);

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a); fclose(fp); w sw

printf("\n");

printf("Reading all the records sequentially\n");

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

for (i=1;i<=10; i++)

{

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

}

fclose(fp);

printf("\n");

printf(" Reading all the records in reverse order\n");

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

for (i=9; i>=0; i--)

{

fseek(fp,sizeof(struct record)*i,SEEK_SET);

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

}

fclose(fp);

printf("\n");

/* use fseek to read alternate record */

printf("Reading every Alternate Record from beginning\n");

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

fseek(fp,0,SEEK_SET);

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

{

fread(&r,sizeof(struct record),1,fp);

/*After each fread moving to next successive record*/

printf("%d\n",r.a);

/*positioning the pointer to current record in the file*/

fseek(fp,sizeof(struct record), SEEK_CUR);

}

fclose(fp);

printf("\n");

printf("Modifying the desired record");

fp=fopen("input.dat","r+");

/*seeking the 5th record in order to read it*/

fseek(fp,sizeof(struct record)*4,SEEK_SET); fread(&r,sizeof(struct record),1,fp);

/*modifying it by some value*/

r.a=-999;

/*seeking the 5th record in order to write*/

fseek(fp,sizeof(struct record)*4,SEEK_SET);

/*writing the modified value*/.

fwrite(&r,sizeof(struct record),1,fp);

fclose(fp);

printf("\n");

/* read the 10 records to insure 4th record was changed */

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

for (i=1;i<=10; i++)

{

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

}

fclose(fp);

printf("\n");

printf("Reading the Last Record\n");

fp=fopen("input.dat","r+");

fseek(fp,sizeof(struct record), SEEK_END);

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

}

Output

Reading First Record

1

Reading all the records sequentially

1

2

3

4

5

6

7

8

9

10

Reading all the records in reverse order

10

9

8

7

6

5

4

3

2

 1

Reading every Alternate Record from beginning

1

3

5

7

9

Modifying the desired record

1

2

3

4

-999

6

7

8

9

10

Reading the Last Record

10

In above program we have used fseek with different modes. The output itself is self explanatory!!

Reading the characters from the file and printing them on console using getc()

test.cpp

/*************************************************************

Reading the contents of the file using getc and printing them on the console

***********************************************************/

#include <stdio.h>

void main()

{

FILE *fp;

int ch;

fp = fopen("d:\input.dat","r");

ch = getc(fp);

while (ch!= EOF)

{

putchar(ch);

ch= getc(fp);

}

fclose(fp);

} 090

Before running this program we should create an input file as d:\input.dat which is as given below -

input.dat

D

A

T
A
S
T
R
U
C
T
R
E
S
Output

D

A

T

A

 S

T

R

U

C

E

 R

E

S

Program Explanation :

In above program we have to first create an input file say input.dat and store some characters in it. Then the test.cpp is written in which we are opening the input.dat file in reading mode using fopen(). By using getc(ch) function we can read the file character by character. The putchar() is a function for printing a single character on console. The EOF is a marker that indicates end of file. At the end of program the file is closed using fclose().

 /***********************************************************

Program for counting total number of lines and total number of characters from the input file

************************************************************/

#include <stdio.h>

#include<conio.h>

void main()

{

FILE *fp;

int ch,chara,lines;

char fname[40];

clrscr();

lines = 0;

chara = 0;

printf("Enter file name: "); gets(fname);

fp = fopen( fname, "r" );

if (fp ===NULL)

{

printf("Error: Cannot open %s \n", fname );

return;

}

ch= getc( fp);

while (ch != EOF)

{

if (ch=='\n')/*if new line char is read*/

lines++;/* increment the counter for that*/

chara++;/*increment no. of characters */

ch=getc(fp);

}

{

fclose(fp);

printf("\n In File %s ",fname);

if (chara != 0)

{

printf("\n Total number of characters = %d\n", chara);

printf("\n Total number of lines = %d", lines );

}

}

Input.dat

hello students

we are learning

C and

Files

Output

Enter file name: d:\input.dat

In File d:\input.dat

Total number of characters = 42

Total number of lines = 4

Use of putw and getw

The putw is a function useful for inputting the integer value to the file and getw is a function used to read the integer value from the input file

/**********************************************************

Program using putw and getw

**********************************************************/

#include <stdio.h>

#include<conio.h>

#include<io.h>

void main()

{

FILE *fp;

int roll;

char fname[40];

clrscr();

printf("Enter file name: ");

gets(fname);

fp = fopen( fname, "w" );

if (fp==NULL)

{

printf("Error: Cannot open %s \n", fname );

return;

}

printf("\n Enter some Roll number");

scanf("%d", &roll);

putw(roll,fp);

fclose(fp);

fp=fopen(fname,"r");

printf("\n The contents in the file %s are..\n",fname);

roll=getw(fp);

printf("\n%d",roll);

fclose(fp);

getch();

}

Output

Enter file name: d:\input.dat

Enter some Roll number 10

The contents in the file d:\input.dat are... 10

Use of fprintf and fscanf

The purpose of fprintf is to write the contents to the file. That's why we have to open the file in write mode. Following program illustrates the idea of using fprintf.

test.cpp

/************************************************************

Program for writing the contents to some input file using fprintf

*************************************************************/

#include <stdio.h>

#include<conio.h>

void main()

{

FILE *fp;

int roll;

char fname[40],name [40]="ABC";

float marks;

clrscr();

roll=5;

marks=10.1;

printf("Enter file name: ");

gets(fname);

fp = fopen( fname, "w");

if (fp == NULL)

{

printf("Error: Cannot open %s \n", fname);

return;

}

fprintf(fp,"%d\n%s\n%f", roll,name,marks);

fclose(fp);

}

Output

Enter file name: d:\input.dat

The input file d:\input.dat will have some contents written by our program test.cpp. Hence input.dat file is

d:\Input.dat

5

ABC

10.100000

The same program can be modified by adding fscanf. The purpose of fscanf is to read the contents from the input file. We will

1. Open the input file in writing mode.

2. Write the contents to input file using fprintf.

3. Close the file.

4. Reopen the file in reading mode.

5. Using fscanf we will read the contents from the input file.

6. Print them on the console.

/***********************************************************

The use of fprintf and fscanf for writing to the file And reading from the file

********************************************************/

#include <stdio.h>

#include<conio.h>

void main()

{

FILE *fp;

int roll;

char fname[40],name [40]="ABC";

float marks;

clrscr();

roll=5;

marks=10.1;

printf("Enter file name: "); gets(fname);

fp = fopen( fname, "w" );"

if (fp == NULL)

{

printf("Error: Cannot open %s \n", fname);

 return;

}

fprintf(fp,"%d\n%s\n%f", roll,name,marks); ni

fclose(fp);

fp=fopen(fname,"r");

printf("\n The contents in the file %s are... \n",fname);

 while(!feof(fp))

{

fscanf(fp,"%d\n%s\n%f",&roll,name,&marks);

printf("%d\n%s\n%f", roll,name,marks);

}

getch();

}

Output

Enter file name: d:\input.dat

The contents in the file d:\input.dat are...

5

ABC

10.100000

Detecting End of File

The end of file is detected using a macro EOF (i.e. End Of File) when this condition occurs then we should not read the contents further.

For example:

#include<stdio.h>

void main()

{

FILE *fp;

char c;

fp = fopen("try.c","r");

c = getc(fp);

while (c!= EOF)

{

putchar( c );

c = getc (fp);

}

fclose(fp);

}

In above program "try.c" file is first created in which we have to store some characters. Another way of detecting end of file is use of feof() function. In this function the file pointer is passed as an argument.

For example :

The syntax is

feof(file_pointer);

Let us see the C program based on it.

#include<stdio.h>

void main()

{

FILE *fp;

char c;

fp = fopen("try.c","r");

c = getc(fp);

while (!feof(fp) )/* feof returns 1 on detecting end of file */

{

putchar( c );

ic = getc (fp);

}

fclose(fp);

}

Review Questions

1. Explain any four functions used for file handling.

2. Explain the different modes of operating a file in C using fopen() function.

 

3. Sequential File Organization

For understanding the concept of sequential file organization consider one example : We want to store the marks of 10 students in a file. We will organize the file in following manner


The C program is as given below -

/***********************************************************

Implementation of various file operations such as create, display, search and modification on student database with USN,Name and marks of three subjects

*************************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<conio.h>

struct record

{

int USN;

char name[20];

int marks1,marks2, marks3;

};

struct record r;

FILE *fp;

void main()

{

int n,choice;

char ch;

void Create_file(int);

 void Display_file(int);

 void Modify_file();

struct record *Search_file();

clrscr();

printf("\n How many Records are there in the file?");

scanf("%d",&n);

do

{

clrscr();

printf("\n\t Main Menu");

printf("\n1. Create a file");

printf("\n2. Display a file");

printf("\n3. Search a file");

printf("\n4. Modify a file");

printf("\n5. Exit");

printf("\n Enter Your Choice ");

scanf("%d", &choice);

switch(choice)

{

case 1: Create_file(n);

break;

case 2: Display_file(n);

break;

case 3: r=*Search_file();

printf("\n USN Name marks1 marks2 marks3\n");

printf("\n---------\n");

flushall();

printf("%d %S %d %d %d \n",r.USN, r. name, r. marks1, r. marks2,r.marks3);

printf("\n-----------------\n”);

break;

case 4: Modify_file();

break;

case 5 exit(0);

}

printf("\n Do You want To Continue?");

ch=getch();

} while (ch=='y' || ch=='Y');

getch();

}

void Create_file(int n)

{

int i;

fp=fopen("stud.dat", "a+");

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

{

printf("\n Enter The name of the student ");

flushall();

gets(r.name);

printf("\n Enter University Seat Number ");

scanf("%d", &r.USN);

printf("\n Enter marks for First Subject ");

scanf("%d", &r.marks1);

printf("\n Enter marks for second Subject ");

scanf("%d", &r.marks2);

printf("\n Enter marks for Third Subject ");

scanf("%d", &r.marks3);

fwrite(&r,sizeof(struct record),1,fp);

}

fclose(fp);

}

void Display_file(int n)

{

int i;

printf("\nReading all the records sequentially\n");

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

printf("\n USN Name marks1 marks2 marks3\n");

printf("\n------\n");

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

{

fread(&r,sizeof(struct record),1,fp);

flushall();

printf("%d %S %d %d %d \n",r.USN,r.name, r. marks1, r. marks2,r.marks3);

}

printf("\n------------------\n");

fclose(fp);

}

void Modify_file()

{

int i;

int key,new_USN,new_marks1,new_marks2,new_marks3;

char new_name[20];

printf("Modifying the desired record");

printf("\n Enter the University Seat Number for modification of record ");

scanf("%d", &key);

fp=fopen("stud.dat","r+");

i=0;

while(!feof(fp))

{

fread(&r,sizeof(struct record),1,fp);

if(r.USN==key)

{

fseek(fp,sizeof(struct record)*i, SEEK_SET);

printf("\n Enter the new record");

printf("\n Enter new name ");

flushall();

gets(new_name);

printf("\n Enter New USN "); scanf("%d",&new_USN);

printf("\n Enter new marks1 ");

scanf("%d",&new_marks1);

printf("\n Enter new marks2 ");

 scanf("%d", &new_marks2);

printf("\n Enter new marks3 ");

scanf("%d", &new_marks3);

r.USN=new_USN;

strcpy(r.name,new_name);

r.marks1=new_marks1;

r.marks2=new_marks2;

r.marks3=new_marks3;

fseek(fp,sizeof(struct record)*i, SEEK_SET);

fwrite(&r,sizeof(struct record),1,fp);

}

i++;

}

fclose(fp);

}

struct record *Search_file()

{

int key,i;

printf("\n Enter the University Seat Number for Searching the record ");

scanf("%d", &key);

fp=fopen("stud.dat","r+");

i=0;

while(!feof(fp))

{

fread(&r,sizeof(struct record),1,fp);

if(r.USN==key)

{

fseek(fp,sizeof(struct record)*i, SEEK_SET);

fclose(fp);

return &r;

}

i++;

}

printf("\n The Record is not present ");

return NULL;

}

Output

How many Records are there in the file?5

Main Menu

1. Create a file

2. Display a file

3. Search a file

4. Modify a file

5. Exit

Enter Your Choice 1

Enter The name of the student aaa

Enter University Seat Number 1

Enter marks for First Subject 40

Enter marks for second Subject 50

Enter marks for Third Subject 60

Enter The name of the student bbb

 Enter University Seat Number 2

Enter marks for First Subject 55

Enter marks for second Subject 66

Enter marks for Third Subject 77

Enter The name of the student cccb02

Enter University Seat Number 3

Enter marks for First Subject 99

Enter marks for second Subject 44

 Enter marks for Third Subject 70

Enter The name of the student ddd

Enter University Seat Number 4

Enter marks for First Subject 45

 Enter marks for second Subject 65

 Enter marks for Third Subject 76

Enter The name of the student eee

 Enter University Seat Number 5

 Enter marks for First Subject 32

Enter marks for second Subject 43

Enter marks for Third Subject 40

Do You want To Continue?

Main Menu

1. Create a file

2. Display a file

3. Search a file

4. Modify a file

5. Exit

Enter Your Choice 2

Reading all the records sequentially


Do You want To Continue?

 

C Programming and Data Structures: Unit II: C Programming – Advanced Features : Tag: : Definition, Syntax, Example C programs - File Handling