c datafiles with programming examples

Data Files
Many applications require the information to be written to or read from an
auxiliary memory device.
Such information is stored on memory device in the form of data file.
Data file allows to store information permanently and access, alter that
information whenever necessary
There are two different types of data files
1. Stream oriented or standard data files
2. System oriented or low level data files
Stream oriented data files are sub divided into two categories
1. Text files consisting fo consecutive characters.
These characters can be interpreted either by the particular library
functions used to transfer the information or by format
specificators within the library functions
These characters can be interpreted as individual data items or
components or strings or numbers
2. Unformatted data files
It organizes data into blocks containing continous bytes of
information.The blocks represent more complex data structures such as an
array and structures.To process stream oriented data files, a separate set of library functions are
used.System oriented data files are more closely related to the computer
operating system.They are much complicated to work upon but more efficient for certain
applications.Separate sets of procedures with accompanying library functions are
required.Opening and closing of a data files
The first step in a stream oriented data files is to establish a buffer area.
The buffer area is the temporary storage which is used while the
information is being transfered between the computer memory and data
files.The buffer area allows information to be read from or written to the data
files.
Establishing buffer area
FILE *fp;
FILE is a special structure type that establishes the buffer area.
FILE need to be declared in upper case
fp is often referred to as stream pointer or simply a stream.
A data file must be opened before it can be created or processed.
This associates the file name with the buffer area
It specifies how data file will utilized
fp = fopen(filename, FiletypeAttribute);
fopen is used to open a file with the given filename, and the way the data
file will be utilized.
The Different File Attributes:
“r” Open an Existing file for read only.
“w” Open a new file for write only.
“a” Open an eisting file for appending.
“r+” Opens a file for reading and writing.
“w+” Open a new file for both reading and writing.
“a+” Open an existing file for both reading and appending.
fopen function returns a pointer to the beginning of the buffer area
associated with the file.
A null is returned, if a file cannot be opened.
A data file must be closed at the end of the program where fclose() is used

fclose(fp)
Creating a data File :
A data file must be created before it can be processed.
A stream oriented data file can be created in two ways Using text editior or word processor.
Writing a program that enters information into the computer and then writes it out to the data file.
To Write data on to a file :
Program
#include<stdio.h>
void main()
{
FILE *fp;
char c;
fp = fopen("File1.dat", "w");
printf("\nEnter Any Data from Your Key Board...\n\n");
do
{
c = getchar();
if(c >= 'a' && c <= 'z')
c = c - 32;
putc(c, fp);
} while(c != '\n');
fclose(fp);
}
To read data from the file :
Program
#include<stdio.h>
void main()
{
FILE *fp;
char c;
fp = fopen("File1.dat", "r");
if(fp == NULL)
printf("\n Error - Can't open the file");
else
do
{
c = getc(fp);
putchar(c);
}while(c != '\n');
fclose(fp);
}
Working with Data Blocks in Files
Structures to be identified for all the following programs.
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;

Program to accept and write the details on to the secondary storage medium
Program
#include<stdio.h>
#include<conio.h>
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;
void main()
{
char reply;
insurance p;
FILE *fp;
fp = fopen("insurance.dat", "w");
do
{
printf("\nInsurance Management System");
printf("\n\nEnter The Insurance Number : ");
scanf("%d", &p.ins_no);
printf("\nEnter Insured Persons Name : ");
scanf("%s", p.name);
printf("\nEnter The Date of Insurance : ");
scanf("%d-%d-%d", &p.doi.d, &p.doi.m, &p.doi.y);
printf("\nEnter The Insurance Amount : ");
scanf("%f",&p.amt);
fprintf(fp, "%d \n %s \n %d - %d - %d \n %f", p.ins_no, p.name,
p.doi.d, p.doi.m, p.doi.y, p.amt);
printf("\nDo You Want to Continue With Another Record [ y / n ] : ");
fflush(stdin);
reply = getchar();
} while(reply == 'y' || reply == 'y');
printf("\nThank U...");
fclose(fp);
}

Program to retrive details from the secondary storage medium and display on
the screen
Program
#include<stdio.h>
#include<conio.h>
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;
void main()
{
FILE *fp;
insurance p;
clrscr();
fp = fopen("c:\\insuranc.dat", "r");
if(fp == NULL)
{
printf("\nFatal Error - Unable to open the File");
exit(0);
}
//fscanf(fp, "%d\n%s\n%d-%d-%d\n %f", p.ins_no, p.name, p.doi.d, p.doi.m, p.doi.y,
p.amt);
//fprintf(fp, "%d \n %s \n %d - %d - %d \n %f", p.ins_no, p.name, p.doi.d, p.doi.m,
p.doi.y, p.amt);
while(!feof(fp))
{
fscanf(fp, "%d\n%s\n%d-%d-%d\n%f", p.ins_no, p.name, p.doi.d, p.doi.m, p.doi.y,
p.amt);
printf("\nThe Insurance Number : %d", p.ins_no);
printf("\nThe Insured Name : %s", p.name);
printf("\nThe Date of Insurance : %d-%d-%d", p.doi.d, p.doi.m, p.doi.y);
printf("\nThe Insured Amount : %f", p.amt);
}
printf("\nFinished Reading");
fclose(fp);
}

Functions for Navigations in Files
rewind (fp)
Moves the file-pointer to the first byte in the file
fread(&NameofStructure, RecordSize, No of Records to Read, FilePointer)
Used to Read the Data from the File.
fwrite(&NameofStructure, RecordSize, No of Records to Write, FilePointer)
Used to Write the Data to the File.
fseek(&FilePointer, Offset, Position)
Used to Move the File Pointer to a Desired Location either forward OR
backward.
Offset:
It is the number of bytes we want to move from the current position in
the file.
Offset is indicated by the file pointer and can be –ve or +ve
Position:
Indicates the location in the file from where one wishes to move.
it can be any of the following values.
0 : Movement from beginning of the file
1 : Movement from the current position in the file
2 : Movement from the end of the file
ftell()
Returns the current file position in the file.
It returns a long value.
Syntax:
LongVariable = ftell(FilePointer);
long int Position;
Position = ftell(fp);
To Add and Append the data
Program
#include<stdio.h>
#include<conio.h>
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;
void main()
{
char reply;
insurance p;
insurance accept_data();
FILE *fp;
clrscr();
printf("\nAdding Records...Please Wait...");
fp = fopen("C:\\insurance.dat", "ab");
if(fp == NULL)
{
printf("\nSorry! Error in Appending the Data...");
exit(1);
}
do
{
p = accept_data();
fwrite(&p, sizeof(p), 1, fp);
printf("\n\nAdd Another Record? [Y/N] : ");
fflush(stdin);
reply = getchar();
}
while(reply == 'Y' || reply == 'y');
fclose(fp);
}
insurance accept_data()
{
insurance x;
printf("\nEnter Insurance Number : ");
scanf("%d", &x.ins_no);
printf("\nEnter The Name of The Person : ");
scanf("%s", x.name);
printf("\nEnter Date of Insurance (DD-MM-YYYY) : ");
scanf("%d-%d-%d", &x.doi.d, &x.doi.m, &x.doi.y);
printf("\nEnter The Amount Insured : ");
scanf("%f",&x.amt);
return(x);
}

To list the records
Program
#include<stdio.h>
#include<conio.h>
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;
void main()
{
insurance p;
FILE *fp;
void display_data(insurance p);
fp = fopen("C:\\insuranc.dat", "rb");
printf("\nListing The Records...Please Wait...");
while(fread(&p, sizeof(p), 1, fp) == 1)
{
display_data(p);
}
fclose(fp);
}
void display_data(insurance p)
{
printf("\nInsurance Number : %d",p.ins_no);
printf("\nInsured Name : %s", p.name);
printf("\nDate of Insurance : %d-%d-%d ",p.doi.d,p.doi.m,p.doi.y);
printf("\nAmout Insured : %f",p.amt);
}

To Modify a record data
Program
#include<stdio.h>
#include<conio.h>
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;
void main()
{
int record_no = 0;
char reply;
insurance p;
insurance accept_data();
char name[20];
FILE *fp;
clrscr();
printf("\nProcess for Modifying the Records.");
fp=fopen("C:\\Insuranc.dat","rb+");
if(fp == NULL)
{
printf("\nSorry! Error in Opening The File...");
exit(1);
}
do
{
printf("\nEnter The Name of The Person to be Modified : ");
scanf("%s",name);
record_no = 0;
while(fread(&p, sizeof(p), 1, fp) == 1)
{
record_no++;
if(strcmp(p.name, name) == 0)
{
printf("\nRecord Found\t Record Number : %d ", record_no);
printf("\nEnter The Modified Data...\n");
p = accept_data();
record_no--;
fseek(fp, record_no * sizeof(fp), 0);
fwrite(&p, sizeof(p), 1, fp);
break;
}
}
rewind(fp);
printf("\nDo You Want to Modify Another Record [y/n]? : ");
fflush(stdin);
reply = getchar();
}
while(reply =='y' || reply == 'y');
fclose(fp);
}
insurance accept_data()
{
insurance x;
printf("\nEnter Insurance Number : ");
scanf("%d", &x.ins_no);
printf("\nEnter The Name of The Person : ");
scanf("%s", x.name);
printf("\nEnter Date of Insurance (DD-MM-YYYY) : ");
scanf("%d-%d-%d", &x.doi.d, &x.doi.m, &x.doi.y);
printf("\nEnter The Amount Insured : ");
scanf("%f",&x.amt);
return(x);
}

To Delete a record in data
Program
#include<stdio.h>
#include<conio.h>
typedef struct
{
int d; /* Day */
int m; /* Month */
int y; /* Year */
} date;
typedef struct
{
int ins_no;
char name[20];
date doi;
float amt;
} insurance;
void main()
{
void display_data(insurance);
insurance p;
char name[20], reply;
FILE *fp1, *fp2;
printf("\nProcess for Deleting a Record.");
do
{
fp1 = fopen("C:\\insuranc.dat", "rb");
fp2 = fopen("C:\\temp.dat", "wb");
if(fp1 == NULL || fp2 == NULL)
{
printf("\nSorry! Error in Opening The File.");
exit(1);
}
printf("\n\nEnter The Name of The Person To Be Deleted : ");
scanf("%s", name);
while(fread(&p, sizeof(p), 1, fp1) == 1)
{
if(strcmp(p.name, name) == 0)
{
printf("\nRecord Found. Displaying Data.\t");
display_data(p);
printf("\nDeleting the Record...Are You Sure [y/n]? : ");
fflush(stdin);
reply = getchar();
break;
}
}
if(reply == 'Y' || reply == 'y')
{
rewind(fp1);
while(fread(&p , sizeof(p), 1, fp1) == 1)
{
if(strcmp(p.name, name) != 0)
fwrite(&p, sizeof(p), 1, fp2);
}
}
fclose(fp1);
fclose(fp2);
remove("C:\\insuranc.dat");
rename("C:\\temp.Dat", "C:\\insuranc.dat");
printf("\nDelete Another Record [y/n] : "); fflush(stdin);
reply = getchar();
} while(reply == 'Y' || reply == 'y');
}
void display_data(insurance p)
{
printf("\nInsurance Number : %d",p.ins_no);
printf("\nInsured Name : %s", p.name);
printf("\nDate of Insurance : %d-%d-%d ", p.doi.d, p.doi.m, p.doi.y);
printf("\nAmout Insured : %f",p.amt);
}