Data file concept
Data file concept:
◦ Definition:-
◦ Many applications require that information be written to or read from an auxiliary storage device.
◦ Such information is stored on the storage device in the form of data file.
◦ Thus, data files allow us to store information permanently and to access later on and alter that information
whenever necessary.
◦ In C, a large number of library functions is available for creating and processing data files.
◦ There are two different types of data files called stream-oriented (or standard) data files(data is stored in same
format as it appears on screen) and system oriented data file(data associated to os). We shall study stream-
oriented data files only in this lesson.
1
Some library functions used in data file
1. fopen()-------------------------------→opens the new file
2. fclose()-------------------------------→closes the opened file
3. getc()--------------------------------→it reads a character from data file
4. Putc()----------------------------------→it writes a character to data file
5. getw()------------------------------→ it reads an integer number from data file
6. putw()-----------------------------→it writes an integer to data file
7. fscanf()---------------------------→it reads formatted data from data file
8. printf()--------------------------------→it writes formatted data to data file
9. fread()----------------------------------→it reads record from data file (used with struct)
10. fwrite()------------------------------------.. It writes record to data file(used with struct)
2
Different mode of working with file
❖r-----------------→used for reading data
❖w---------------→used for writing data
❖a------------------→used for appending data/adding extra data without deleting existing data
❖r+--------------------→used for reading and writing both
❖w+-----------------→used for reading and writing both
❖a+---------------------→used for reading and appending both
etc
3
Steps to work with data file
Step1: define the file pointer.
FILE *p;
Step 2: open the file using fopen() in particular mode (‘r’ or ‘w’ or ‘a’ etc)
p=fopen(“file.txt”,”r”);
note:if the file is opened first time it must be opened in ‘w’ or ‘a’ mode to store data
Necessary inputs we can do here.
Step 3: write/read data from opened file using functions.
right now we performing read operation so we can use fread or fscanf etc.
fscanf(p,’’%s”,name);
Step4:now close the file using fclose() function.
fclose(p);
4
Working with getc() and putc() function
getc(): it is used to read data.
Syntax:
◦ Variable =getc(pointer);
◦ eg
ch=getc(fp);
putc():it is used to write data.
Syntax:
◦ putc (variable,pointer);
◦ eg
putc(ch,fp);
5
getc() and putc() example
//using putc() to store data(one character) and getc() to read (one character)that data from an opened //file
#include <stdio.h>
int main()
{
FILE *p; //pointer declaration
char ch;
p=fopen("data.txt","w"); //file opening in write mode
printf("first we store/write data in an opened file\n");
printf("press ctrl+z to exit\n");
while((ch=getchar())!=EOF) //gets one character until you press ctrl+z/terminate the input
{
putc(ch,p); // write the entered character in that file
}
fclose(p); //closes the file
printf("data stored successfully!!!\n");
printf("now we are going to read that stored data\n");
p=fopen("data.txt","r"); // openes the file in read only mode
while((ch=getc(p))!=EOF) //read a character using getc from opened file.
{
putchar(ch); //prints that character on screen
}
fclose(p); //closes the file
return 0;
}
6
Working with getw() and putw() function
getw(): it is used to read an integer
Syntax:
Variable =getw(pointer);
eg
ch=getw(fp);
putw():it is used to write an integer.
Syntax:
putw (variable,pointer);
eg
putw(ch,fp);
7
getw() and putw() function example
//using putw() to store data(one integer) and getw() to read (one integer)that data from an opened file
#include <stdio.h>
#include<stdlib.h> // header file for system("cls")
int main()
{
FILE *p; //pointer declaration
char ch;
int i;
system("cls"); //clears the screen/console
p=fopen("data1.txt","w"); //file opening in write mode
printf("first we store/write data in an opened file\n");
for(i=0;i<=40;i++) //executes the loop
{
// fprintf(p,"%d\n",i); // write the entered integer in that file
putw(i,p);
}
fclose(p); //closes the file
printf("data/numbers stored successfully!!!\n");
printf("now we are going to read that stored data\n");
p=fopen("data1.txt","r"); // openes the file in read only mode
while((i=getw(p))!=EOF) //read an integer using getw from opened file.
{
printf("%d,",i); //prints that integer on screen
}
fclose(p); //closes the file
return 0;
}
8
Working with fscanf() and fprintf() function
fprintf(): It is used to write data/records in an opened data file i.e it writes data in an opened data file.
Syntax:
fprintf(FILE *stream, constant char *format);
example:
FILE *k;
k=fopen("data.txt","w");
fprintf(k,"%s %s %s","hello","world", "of c");
this writes data (mentioned above) in an opened file data.txt.
fscan(): It is used to read data/records from opened data file.
Syntax:
fscanf(FILE *stream, constant char *format,...);
example:
FILE *k;
k=fopen("data.txt","r");
char string[100];
fscanf(k,"%s %s %s",string,string,string);
this reads data (mentioned above) from opened file data.txt
9
fprintf() and fscanf() example
//using fprintf() to store data(one integer) and fscanf()() to
}
read (one integer)that data from an opened //file
fclose(p); //closes the file
#include <stdio.h>
getch();
#include<stdlib.h> // header file for
printf("data/numbers stored successfully!!!\n");
system("cls")
printf("now we are going to read that stored data\n");
#include<conio.h>
p=fopen("data1.txt","r");
int main()
// openes the file in read only mode
{
while((fscanf(p,"%d",&i))!=EOF) //read an integer using fscanf()
FILE *p; //pointer declaration
from opened file util it ends.
char ch;
{
int i;
system("cls"); //clears the screen/console
printf("%d,",i); //prints that integer on screen
p=fopen("data1.txt","w"); //file opening in write
}
mode
fclose(p); //closes the file
printf("first we store/write data in an opened file\n");
return 0;
for(i=0;i<=40;i++) //executes the loop
}
{
fprintf(p,"%d\n",i);
// write the entered integer in that file
10
Working with fread() and fwrite() function
fwrite(): It is used to write data/records in an opened data file i.e it writes data in an opened data
file.it is used with struct tag.
Syntax:
fwrite(&variable,sizeof(tag),1,file pointer);
fread(): It is used to read data/records from opened data file. .it is used with struct tag
Syntax:
fread(&variable,sizeof(tag),1,file pointer);
11
Example of fread() and fwrite() function
//program to store and read employee name and salary using fread() printf("want to continue (y/n):=");//prints message
and fwrite() choice=getche(); //gets a character
#include <stdio.h> }while(choice!='n'); //writing repeats as you enter 'y'
#include <stdlib.h>
struct employee
printf("\n writing process completed successfully\n");
{ fclose(k); //closing of file
char name[50]; //closing data file
float salary; printf('-----------------------');
}var; printf("reading data\n");
int main() k=fopen("employee.txt","r");//file opening
{
FILE *k; // pointer for file declaration
char choice; //identifier declaration
while((fread(&var,sizeof(var),1,k))==1)// fread() reads the records till it
is true.
k=fopen("employee.txt","w"); //file opening //As it becomes less than 1, it stops
do {
{ printf("salary=%f and name=%s\n",var.salary,var.name);//prints the
printf("\n enter salary\n"); struct value
scanf("%f",&var.salary); }
printf("enter name\n"); // getting inputs
scanf("%s",var.name);
fclose(k); //closing of file.
fwrite(&var,sizeof(var),1,k); //writing data to data file getch();
return 0;
} 12
Types of data file processing
We have two types of data file processing.
1 sequential file processing:
->A sequential file is a sequence of records. The records may or may not be kept in sorted order in the sequence.
->The simplest way that C programming information is stored in a file is sequentially, one byte after the other. The file
contains one long stream of data in bits.
->It is slower than random.
->Writing is simpler.
2 Random file processing:-
◦ Random Access to a file means that the computer system can read or write information anywhere in the data file. It uses
indexing technique.
◦ IT deals with text and binary file.
◦ Some additional functions (fseek(),ftell etc) are needed to write program.
◦ It is faster than sequential. Writer is complex.
13
Random file processing:
Concept of ftell(),rewind() and fseek() functions
ftell():-
It tells us the current position of pointer in the term of byte.
syntax:
variable =ftell(pointer);
rewind():-
It takes file pointer to the start of the file.
Syntax:
rewind(pointer);
fseek():-
It takes file pointer to the desire location.
Syntax:
fseek(pointer, offset, position);
Here offset means bytes we are going to shift the pointer
Position can be SEEK_SET,SEEK_CUR,SEEK_END.
14
Example of
ftell(),rewind() and fseek() functions
#include <stdio.h> printf("\n writing process completed successfully\n");
#include<conio.h> rewind(k);
struct employee //struct tag fclose(k); //closing of file //closing data file
{ printf("-----------------------\n");
int employee_id; printf("reading data\n"); //opening file in read mode
k=fopen("employees.txt","r"); //file opening
float employee_salary;
char employee_name[50];
while((fread(&var,sizeof(var),1,k))==1)// fread() reads the records till it is true.
}var; //variable //As it becomes less than 1, it stops
int main() {
{ printf("employee id=%d,employee salary=%f,employee
FILE *k; // pointer for file declaration name=%s\n",var.employee_id,var.employee_salary,var.employee_name);//prints the struct value
char choice; //identifier declaration }
k=fopen("employees.txt","w"); //file opening in write mode //location=ftell(k);
do printf("the location using ftell=%ld\n",ftell(k));// tells us the location of pointer.
{ fseek(k,2,SEEK_SET); // sets the pointer to second position
printf("\n enter employee id\n"); printf("the location after using seek_set=%ld\n",ftell(k));
scanf("%d",&var.employee_id); fseek(k,0,SEEK_CUR); //takes the current location of pointer.
//IF we take any other value than 0 ,
printf("enter employee salary\n");
//it adds that to previous location and displays that
scanf("%f",&var.employee_salary);
printf("the location after using seek_cur=%ld\n",ftell(k));
printf("enter employee name\n"); // getting inputs fseek(k,0,SEEK_END); //takes position of pointer is at the end.
scanf("%s",var.employee_name); printf("the location after using seek_end=%ld\n",ftell(k));
fwrite(&var,sizeof(var),1,k);; //writing data to data file rewind(k); //takes the pointer to 0 location i.e. beginning
printf("want to continue (y/n):=");//prints message printf("the location=%ld\n",ftell(k));
choice=getche(); //gets a character fclose(k); //closing of file.
}while(choice!='n'); //writing repeats as you enter 'y' getch();
return 0;
15
}
Concept of rename() and remove() functions
rename():-
◦ It is used to rename the file.
Syntax:
rename(“old name”,”new name”);
Remove():- it is used to remove the file.
syntax:
remove(“file name”);
16
Example of rename() and remove() functions
//understanding remove() function
rename() example:- #include <stdio.h>
◦ //understanding rename() function #include<conio.h>
#include <stdio.h>
#include<conio.h> int main()
{
char file_name[40];
int main() FILE *k;
{ printf("enter file name with extension .txt\n");
char first_name[40],second_name[40]; gets(file_name);
printf("enter file name with extension .txt\n"); k=fopen("file_name","w");
gets(first_name); if(k==NULL)
printf("enter name to be changed\n"); {
gets(second_name); printf("sorry, not found\n ");
rename("first_name","second_name"); }
printf("the entered file renamed successfully"); else
getch(); {
remove("file_name");
return 0;
printf("the entered file removed successfully");
} }
◦ Remove example: getch();
return 0;
}
17
Some important questions
1. Explain about any four data file handling functions with examples.
2. What is file pointer? Explain its importance in data file handling.
3. WAP to store book's name,price and author's name in a file namd 'book.dat' and then read and display
on monitor.
4.WAP to store student's name, grade and roll number in a file named ‘student.dat' and then read and
display on monitor.
5. WAP to store book's name,price and author's name in a file namd 'book.dat’
6.A file named book.txt contains information of some books (book name and price). Now read and display
all information on monitor.
7.wap to understand remove() and rename() functions.
18
Thank you for your attention!
If you have any question, please forward it.
19