SlideShare a Scribd company logo
File Handling
• Console oriented I/O functions use keyboard as
input device and monitor as output device.
• The I/O functions like printf(), scanf(), getchar(),
putchar(), gets(), puts()
• Problem:
1. Entire data is lost when either the program is
terminated or the computer is turned off.
2. When the volume of data to be entered is large, it
takes a lot of time to enter the data.
3. If user makes a mistake while entering data, whole
data has to be re-entered.
• Solution: File
Background
2
• File
is a place on the disk (not memory) where a
group of related data is stored. Also called
data files.
• The Data File
allows us to store information permanently
and to access and alter that information
whenever necessary.
Concept of file
3
Classification of disk/file I/O functions
Disk I/O Functions
High-level Low-level
Text Binary
Formatted Unformatted UnformattedFormatted
4
Function name Operation
fopen() •Creates a new file for use
•Opens an existing file for use
fclose() •Closes a file which was opened for use
fgetc() •Reads a character from a file
fputc() •Writes a character to a file
fprintf() •Writes a set of data values to a file
fscanf() •Reads a set of data values from a file
fseek() •Sets the position to a desired point in the file
ftell() •Gives the current position in the file (in terms of bytes
from the start)
rewind() •Sets the position to the beginning of the file
Some high-level I/O functions
5
• The general format for declaring and opening a file is:
FILE *fp;
fp=fopen(“filename”, “mode”);
• Here, the first statement declares the variable fp as a
“pointer to the data type FILE”.
• The second statement opens the file named filename
with the purpose mode and the beginning address of the
buffer area allocated for the file is stored by file pointer
fp.
• Note: Any no. of files can be opened and used at a time.
Defining and Opening a file
6
• There are mainly six modes:
1. “r” (i.e. read mode)
2. “w” (i.e. write mode)
3. “a” (i.e. append mode)
4. “r+” (i.e. read and write mode)
5. “w+” (i.e. write and read mode)
6. “a+” (i.e. append and read mode)
File Opening Modes
7
• The closing a file ensures that all outstanding
information associated with the file is flushed out from
the buffers and all links to the file are broken.
• In cases where there is a limit to the no. of files that can
be kept open simultaneously, closing of unwanted files
help in opening the required ones.
• Another instance where we have to close a file is when
we want to reopen the same file in different mode.
• The file is closed using library function fclose() as:
fclose(fp);
Closing a file
8
• Once a file is opened, reading out of or writing
to it is accomplished using the standard I/O
functions.
Library Functions for Reading/Writing
from/to a File: File I/O Functions
9
• Using string I/O functions fgets() and fputs(),
data can be read from a file or written to a file
in the form of array of characters.
i. fgets(): is used to read string from file.
Syntax: fgets(string, int_value, fp);
Here, int_value denotes the no. of characters in the string.
ii. fputs(): is used to write string to file.
Syntax: fputs(string, fp);
String Input/Output Functions
10
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("D:test.txt", "w");
if(fp==NULL)
{
printf("n Cannot create file.");
exit(0);
}
else
{
printf("n File is created.");
}
fputs("I study CSIT", fp);
fclose(fp);
getch();
}
11
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char s[100];
clrscr();
fp=fopen("D:test.txt", "r");
if(fp==NULL)
{
printf("n Cannot open file.");
exit(0);
}
else
{
printf("nFile is opened.");
}
fgets(s,19,fp);
printf("n Text from file is:%s", s);
fclose(fp);
getch();
}
12
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("D:test.txt", "a");
if(fp==NULL)
{
printf("n Cannot open file.");
exit(1);
}
else
{
printf("n File is opened.");
}
fputs(“in CAB", fp);
fclose(fp);
getch();
}
13
void main()
{
FILE *fp;
char filename[20];
clrscr();
printf("Enter filename:t");
gets(filename);
fp=fopen(filename, "w");
if(fp==NULL)
{
printf("n Cannot create file.");
exit(1);
}
else
{
printf("n File is created.");
}
getch();
}
// If only filename is given, file is created in C:TCBIN otherwise file is created in the given path.
14
Naming a file
• Using character I/O functions fgetc() and
fputc(), data can be read from file or written
onto file one character at a time.
i. fgetc(): is used to read a character from a file.
Syntax:
char_variable=fgetc(fp);
ii. fputc(): is used to write a character to a file.
Syntax:
fputc(‘character’or character_variable, fp);
Character I/O Functions
15
void main()
{
FILE *fp;
char filename[20];
char c;
clrscr();
printf("Enter filename:t");
gets(filename);
fp=fopen(filename,"w");
if(fp==NULL)
{
printf("n Cannot create file.");
exit();
}
else
printf("n File is created.");
printf("n Enter your text until Enter key:n");
while((c=getchar())!='n')
fputc(c,fp);
fclose(fp);
getch();
} 16
void main()
{
FILE *fp;
char filename[20];
char c;
clrscr();
printf("Enter filename:t");
gets(filename);
fp=fopen(filename, "r");
if(fp==NULL)
{
printf("n Cannot open file.");
exit();
}
printf("n The content of file is:n");
while((c=fgetc(fp))!=EOF)
putchar(c);
fclose(fp);
getch();
}
17
• EOF is a special character (an integer with ASCII
value 26) that indicates that the end-of-file has
been reached. This character can be generated
from the keyboard by typing Ctrl+Z.
• Defined in <stdio.h>
• When we are creating a file, the special character
EOF, is inserted after the last character of the file
by the Operating System.
• Caution: An attempt to read after EOF might
either cause the program to terminate with an
error or result in an infinite loop situation.
18
End-Of-File (EOF)
void main()
{
FILE *fp;
char filename[20];
char c;
clrscr();
printf("Enter filename:t");
gets(filename);
fp=fopen(filename,"a");
if(fp==NULL)
{
printf("n Cannot create or open file.");
exit();
}
printf("nEnter text to append to file %s:n", filename);
while((c=getchar())!='n')
fputc(c,fp);
fclose(fp);
getch();
}
19
void main()
{
FILE *sfp,*dfp;
char sfilename[20],dfilename[20];
char c;
clrscr();
printf("Enter source filename:t");
gets(sfilename);
printf("n Enter destination
filename:t");
gets(dfilename);
sfp=fopen(sfilename,"r");
if(sfp==NULL)
{
printf("nSource file can't be
opened.");
exit();
}
dfp=fopen(dfilename, "w");
if(dfp==NULL)
{
printf("n Destination file cannot
be created or opened.");
exit();
}
while((c=fgetc(sfp))!=EOF)
fputc(c, dfp);
printf("n Copied........");
fclose(dfp);
fclose(sfp);
getch();
}
20
• Given a text file, create another text file
deleting all the vowels (a, e, i, o, u).
Question
21
void main()
{
FILE *fp,*fpp;
char c;
fp=fopen("C:test.txt","r+");
clrscr();
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
fpp=fopen("C:hello.txt","w");
if(fpp==NULL)
{
printf("Cannot create file");
exit();
}
while((c=fgetc(fp))!=EOF)
{
if((c!='a')&&(c!='e')&&(c!='i')&&(
c!='o')&&(c!='u'))
fputc(c, fpp);
}
fclose(fp);
fclose(fpp);
getch();
}
22
• Using formatted I/O functions, fprintf() and
fscanf(), numbers, characters or string can be read
from file or written onto file according to our
requirement format.
i. fprintf(): is formatted output function which is used to
write integer, float, char or string value to a file.
Syntax:
fprintf(fp, “control_string”, list_of_variables);
ii. fscanf(): is formatted input function which is used to
read integer, float, char or string value from a file.
Syntax:
fscanf(fp, “control_string”, &list_of_variables);
23
Formatted I/O Functions
void main()
{
FILE *fp;
char name[20];
int roll;
char address[20];
float marks;
clrscr();
fp=fopen("C:student.txt", "w");
if(fp==NULL)
{
printf("n File cannot be created or opened.");
exit();
}
24
printf("n Enter name of student:t");
gets(name);
printf("n Enter roll number of %s:t", name);
scanf("%d", &roll);
fflush(stdin);
printf("n Enter address of %s:t", name);
gets(address);
printf("n Enter marks of %s:t", name);
scanf("%f", &marks);
printf("n Now writing data to file...");
fprintf(fp, "Name=%sn Roll=%dn Address=%sn Marks=%.2f",
name, roll, address, marks);
printf("n Completed");
fclose(fp);
getch();
}
25
• Here, after providing name of student, we would hit
enter key……No Problem……and then we provide roll
of student……and hit the enter key
again…...Problem…...
• At this time the enter key which is in the keyboard
buffer is read by the gets()/scanf() function for address
(as enter key is a character, n), so that we are able to
fill only the marks.
• To avoid this problem, we use the function fflush().
• It is designed to remove or flush out any data remaining
in the buffer.
26
Use of fflush()
• Define a structure for Vehicle Owner having
data members name, address, telephone
number, vehicle number and license
number. Take the data for ten owners, write
them in file “Own.txt”. Read the data from
the file and display them.
Question
27
struct vehicle_owner
{
char name[20];
char address[20];
long int phone_no;
int vehicle_no;
int license_no;
};
void main()
{
FILE *fp;
struct vehicle_owner vehicle[10], v[10];
int i;
clrscr();
fp=fopen("C:Own.txt","w");
if(fp==NULL)
{
printf("nCannot create file.");
exit();
}
28
for(i=0;i<SIZE;i++)
{
printf("n Enter information about vehicle owner %d",i+1);
printf("n Enter name :t");
gets(vehicle[i].name);
printf("n Enter address:t");
gets(vehicle[i].address);
printf("n Enter telephone no:t");
scanf("%ld", &vehicle[i].phone_no);
printf("n Enter vehicle no:t");
scanf("%d", &vehicle[i].vehicle_no);
printf("n Enter license no:t");
scanf("%d", &vehicle[i].license_no);
fprintf(fp,"%st%st%ldt%dt%dn", vehicle[i].name, vehicle[i].address,
vehicle[i].phone_no, vehicle[i].vehicle_no, vehicle[i].license_no);
fflush(stdin);
}
29
fclose(fp);
fp=fopen("C:Own.txt","r");
for(i=0;i<10;i++)
{
fscanf(fp,"%s %s %ld %d
%d",&v[i].name,&v[i].address,&v[i].phone_no,&v[i].vehicle_no,&v[i].license_
no);
printf("%st%st%ldt%dt%dn",v[i].name,v[i].address,v[i].phone_no,v[i].vehicl
e_no,v[i].license_no);
}
fclose(fp);
getch();
}
• Given a text file, create another text file
deleting the following words “three”, “bad”,
and “time”.
Problem
31
#include <stdio.h>
void main()
{
FILE *fp,*fpp;
char c[10];
fp=fopen("C:test.txt",“r");
clrscr();
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
fpp=fopen("C:hello.txt","w");
if(fpp==NULL)
{
printf("Cannot create file");
exit();
}
while(fscanf(fp,"%s",c)!=EOF)
{
if((strcmp(c,"three")!=0)&&(strcmp(c,"bad")!=0)&&(strcmp(c,"time")!=0))
{
fprintf(fpp,"%s ",c);
}
}
fclose(fp);
fclose(fpp);
getch();
}
32
• Some text file is given, create another text
file replacing the following words “Ram” to
“Hari”, “Sita” to “Gita”, and “Govinda” to
“Shiva”.
Problem
33
#include <stdio.h>
void main()
{
FILE *fp,*fpp;
char c[10];
fp=fopen("C:test.txt","r");
clrscr();
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
fpp=fopen("C:hello.txt","w");
if(fpp==NULL)
{
printf("Cannot create file");
exit();
}
while(fscanf(fp,"%s",c)!=EOF)
{
if(strcmp(c, "Ram")==0)
fprintf(fpp, "Hari ",c);
else if(strcmp(c, "Sita")==0)
fprintf(fpp,"Gita",c);
else if(strcmp(c, "Govinda")==0)
fprintf(fpp, "Shiva",c);
else
fprintf(fpp,"%s ",c);
}
fclose(fp);
fclose(fpp);
getch();
}
34
• Create a program to create a data file and
write the integers from 1 to 20 to this file
and then read the numbers from the file to
display the squares of the stored numbers.
35
Question
#include <stdio.h>
void main()
{
FILE *fp;
register unsigned int i;
unsigned filedata;
clrscr();
fp=fopen("C:data.txt","w");
if(fp==NULL)
{
printf("nCannot create data file.");
exit();
}
for(i=1;i<21;i++)
{
fprintf(fp,"%ut",i);
}
fclose(fp);
fp=fopen("C:data.txt","r");
printf("nThe squares of the stored numbers are:t");
for(i=1;i<21;i++)
{
fscanf(fp,"%u",&filedata);
filedata=filedata*filedata;
printf("%ut", filedata);
}
getch();
}
36
• A file named DATA contains a series of
integer numbers. Code a program to read
these numbers and then write all odd
numbers to a file to be called ODD and all
even numbers to a file to be called EVEN.
37
Question
#include <stdio.h>
void main()
{
FILE *fpdata;
FILE *fpodd;
FILE *fpeven;
int i,n;
int num;
clrscr();
printf("nHow many integers you want in data file?:t");
scanf("%d",&n);
printf("nEnter %d integers:t",n);
fpdata=fopen("C:DATA.txt","w");
for(i=0;i<n;i++)
{
scanf("%d",&num);
fprintf(fpdata,"%dn",num);
}
fclose(fpdata);
fpdata=fopen("C:DATA.txt","r");
fpodd=fopen("C:ODD.txt","w");
fpeven=fopen("C:EVEN.txt","w");
38
for(i=0;i<n;i++)
{
fscanf(fpdata,"%d", &num);
if(num%2==0)
fprintf(fpeven,"%dt", num);
else
fprintf(fpodd,"%dt", num);
}
fclose(fpdata);
fclose(fpodd);
fclose(fpeven);
getch();
}
39
• Trying to read beyond the end-of-file mark.
• Trying to use a file that has not been opened.
• Trying to perform an operation on a file, when
the file is opened for another type of operation.
• Opening a file with an invalid filename.
40
Error situations during I/O operations
• I/O errors can be detected using two status-inquiry
library functions: feof() and ferror().
• feof(): It is used to test for an end-of-file condition. It
takes a FILE pointer as its only argument and returns a
nonzero integer value if all of the data from the
specified file has been read, and returns zero otherwise.
If fp is a pointer to a file that has just been opened for
reading, then the statement
if(feof(fp))
printf(“End of data”);
would display the message “End of data” on reaching
the end-of-file condition.
41
Error handling functions
• ferror(): This function reports the status of the file
indicated. It takes a FILE pointer as its argument
and returns a nonzero integer if an error has been
detected up to that point, during processing. It
returns zero otherwise. So the statement
if(ferror(fp)!=0)
printf(“An error has occurred”);
would print the error message, if the reading is
not successful.
42
Error handling functions…
void main()
{
FILE *fp1;
char *filename;
int i, num;
clrscr();
fp1=fopen("C:test.txt", "w");
for(i=10;i<=100;i += 10)
{
fprintf(fp1,"%dt", i);
}
fclose(fp1);
printf("n Enter filename:t"); //Type C:test.txt
open_file:
scanf("%s", filename);
43
if((fp1=fopen(filename,"r"))==NULL)
{
printf("nAn error occured while opening the file.");
printf("nType filename again:t");
goto open_file;
}
else
for(i=1;i<=20;i++)
{
fscanf(fp1,"%d", &num);
if(feof(fp1))
{
printf("nRan out of data.");
break;
}
else
printf("%dn", num);
}
fclose(fp1);
getch();
}
44
void main()
{
FILE *fp;
int num;
clrscr();
fp = fopen("DUMMY.FIL", "w");
/* force an error condition by attempting to read */
fscanf(fp,"%d", &num);
if (ferror(fp)!=0)
{
printf("Error reading from DUMMY.FILn");
}
fclose(fp);
getch();
}
45
• The binary files organize data into blocks
containing contiguous bytes of information.
• In binary file, the opening mode of text file is
appended by a character b i.e.
i. “r” is replaced by “rb”
ii. “w” is replaced by “wb”
iii. “a” is replaced by “ab”
iv. “r+” is replaced by “r+b”
v. “w+” is replaced by “w+b”
vi. “a+” is replaced by “a+b”
46
Binary Data Files
Note: For text mode we can write
“rt” in place of “r”, “wt” in place of
“w”and so on. However, it is
unnessary because default mode is
text mode
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("C:test.txt","w+b");
if(fp==NULL)
{
printf("nCannot create file.");
exit();
}
fputs("I study B.Sc. CSIT", fp);
fclose(fp);
getch();
}
47
• Analyze with 3 factors:
I. How newlines (n) are stored?
II. How end-of-file is indicated?
III. How numbers are stored in the file?
48
So, what’s the difference between text
mode and binary mode and which mode to
use???
/*Count no. of characters, spaces,
and newlines in a file*/
void main()
{
FILE *fp;
char text[100];
char c;
int noc=0,nos=0,nol=0;
fp=fopen("C:poem.txt", "r");
if(fp==NULL)
{
printf("nCannot create or open
file.");
exit();
}
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
noc++;
if(c==' ')
nos++;
if(c=='n')
nol++;
}
fclose(fp);
printf("n No. of characters:%d",
noc);
printf("n No. of spaces:%d", nos);
printf("n No. of lines:%d", nol);
getch();
}
49
Johnny Johnny
Yes Papa
Eating Sugar
No Papa
Telling Lies
No Papa
Open Your Mouth
hahaha
50
The poem.txt file contains:
So output is:
No. of characters=87
No. of spaces=8
No. of lines=7
which is correct.
Now, go to DOS shell and use the
DIR command in C-drive to view the
no. of characters (bytes) that the file
poem.txt occupies which is 94.
• In text mode, a newline character is converted into the
carriage return-linefeed combination before being
written to disk.
• Likewise, the carriage return-linefeed combination on
the disk is converted back into a newline when the file
is read by a C program.
• However, if a file is opened in binary mode, as opposed
to text mode, these conversions do not take place.
• In binary mode, each end of line is signified by a
carriage return-linefeed combination and is counted as
two characters in binary mode (similar to DIR
command in DOS).
51
First factor
52
/*Count no. of characters, spaces,
and newlines in a file*/
void main()
{
FILE *fp;
char text[100];
char c;
int noc=0,nos=0,nol=0;
fp=fopen("C:poem.txt", "rb");
if(fp==NULL)
{
printf("nCannot create or open
file.");
exit();
}
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
noc++;
if(c==' ')
nos++;
if(c=='n')
nol++;
}
fclose(fp);
printf("n No. of characters:%d",
noc);
printf("n No. of spaces:%d", nos);
printf("n No. of lines:%d", nol);
getch();
}
• In text mode, a special character EOF whose
ASCII value is 26 is inserted after the last
character in the file to mark the end of file.
• However, there is no such special character
present in the binary mode files to mark the
end of file.
• The binary mode files keep track of the end of
file from the number of characters present in
the directory entry of the file.
53
Second Factor
• In text mode, the text and numbers are stored as string of
characters such that the number 12345 will occupy 5 bytes
(1 byte/character).
• Similarly 1234.56 occupies 7 bytes on disk in text mode.
• However, in binary mode the numbers are stored in the
same way as they are stored in RAM so that the number
12345 occupies only 2 bytes and 1234.56 occupies only 4
bytes on disk in binary mode.
• Therefore, when large amount of numerical data is to be
stored onto disk, binary mode is suitable by using functions
fread() and fwrite() instead of fprintf() and fscanf().
54
Third Factor
• The character I/O and string I/O functions allow
reading/writing of character data only, while the
formatted I/O functions allow reading/writing of
character data and numeric data both.
• Problem: Numbers are always stored as a
sequence of characters using these I/O functions
(irrespective of whether text mode or binary mode
is being used), so that they occupy a lot of disk
space.
55
Record I/O……Background Problems
• Another Problem: There is no direct way to read and write
complex data types such as arrays and structures. Arrays
and structures are handled by writing/reading one element
at a time or using loops, but this approach is inefficient.
• Example:
56
#include <stdio.h>
void main()
{
FILE *fp;
char another='Y';
struct emp
{
char name[40];
int age;
float salary;
};
struct emp e;
fp=fopen("c:emp.dat","wb");
if(fp==NULL)
{
puts("Cannot create or open file");
exit();
}
while(another=='Y')
{
printf("nEnter name, age and basic salary");
scanf("%s %d %f",e.name,&e.age,&e.salary);
fprintf(fp,"%st%dt%f",e.name,e.age,e.salary);
printf("nAdd another record(Y/N):t");
fflush(stdin);
another=getche();
}
fclose(fp);
getch();
}
Here, if the no. of fields in the structure
increase (say by adding address, house
rent allowance etc.), writing structures
using fprintf(), or reading them using
fscanf(), becomes quite clumsy.
• Defined in <stdio.h>
• fwrite(): is used for record output.
Syntax:
fwrite(&p, size_of_array_or_structure,
no._of_array_or_structure, fp);
• fread(): is used for record input.
Syntax:
fread (&p, size_of_array_or_structure,
no._of_array_or_structure, fp);
57
Record Input/Output Functions
#include <stdio.h>
void main()
{
FILE *fp;
char another='Y';
struct emp
{
char name[40];
int age;
float salary;
};
struct emp e;
clrscr();
fp=fopen("c:emp.dat","wb");
if(fp==NULL)
{
puts("Cannot create or open file");
exit();
}
while(another=='Y'||another=='y')
{
printf("n Enter name, age and basic salary:");
scanf("%s %d %f", e.name, &e.age,
&e.salary);
fwrite(&e,sizeof(e),1,fp);
printf("n Add another record(Y/N):t");
fflush(stdin);
another=getche();
}
fclose(fp);
fp=fopen("c:emp.dat","rb");
if(fp==NULL)
{
puts("Cannot create or open file");
exit();
}
while(fread(&e,sizeof(e),1,fp)==1)
{
printf("n%st%dt%f", e.name, e.age,
e.salary);
}
fclose(fp);
getch();
}
58
#include <stdio.h>
void main()
{
FILE *fp;
struct emp
{
char name[40];
int age;
float salary;
};
struct emp e[2],ee[2];
int i;
float temp;
clrscr();
fp=fopen("c:employee.dat","wb");
if(fp==NULL)
{
puts("Cannot create or open file");
exit();
}
for(i=0;i<2;i++)
{
printf("nEnter name, age and basic salary:");
scanf("%s %d %f",e[i].name,&e[i].age,&temp);
e[i].salary=temp;
fflush(stdin);
}
fwrite(&e,sizeof(e),2,fp);
fclose(fp);
fp=fopen("c:employee.dat","rb");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
fread(&ee,sizeof(ee),2,fp)
for(i=0;i<2;i++)
printf("n%st%dt%.2f", ee[i].name, ee[i].age,
ee[i].salary);
fclose(fp);
getch();
}
59
• Till now, reading and writing data from/to a
file has been done sequentially.
• But we may need to access a particular data
item placed in any location without starting
from the beginning.
• This is called random access or direct access.
60
Random Access in a File (Direct Access)
• A file pointer is a pointer to a particular byte in a file.
• While opening a file in write mode, the file pointer is at the
beginning of the file, and whenever we write to a file, the
file pointer moves to the end of the data items written so
that writing can continue from that point.
• While opening a file in read mode, the file pointer is at the
beginning of the file, and whenever we read from a file, the
file pointer moves to the beginning of the next data item so
that reading cam continue from that point.
• While opening a file in append mode, the file pointer is at
the end of the existing file, so that new data items can be
written from there onwards.
• If we are able to move the file pointer according as our
need, then any data item can be read from a file or written
onto a file randomly…………Random Access
61
Use of file pointer for random access…
1. ftell(): This function takes a file pointer as
argument and returns a number of type long,
that indicates the current position of the file
pointer within the file. This function is useful
in saving the current position of a file, which
can be used later in the program.
Syntax
n = ftell(fp);
Here, n would give the relative offset (in bytes) of
the current position. This means that n bytes have
already been read (or written).
62
Functions used in random access
2. rewind():This function takes a file pointer as
argument and resets the current position of the
file pointer to the start of the file.
Syntax: rewind(fp);
 What these statements do?: rewind(fp);
n=ftell(fp);
• Here, n would be assigned 0, because file
position has been set to the start of the file by
rewind().
• Note: The first byte in the file is numbered as 0,
second as 1, and so on.
63
Functions used in random access
3. fseek(): This function is used to move the file pointer
to a desired position within a file.
Syntax
fseek(fp, offset, position);
where fp is a file pointer, offset is a number or
variable data type long, and position is an integer
number
• The offset specifies the number of positions (bytes) to
be moved from the location specified by position.
• The position can have one of the following 3 values:
64
Functions used in random access…
Value Meaning
0 Beginning of file
1 Current position
2 End of file
• The offset may be positive, meaning move
forwards, or negative, meaning move backwards.
• Examples:
65
fseek()…
Statement Meaning
fseek(fp, 0L, 0); Move file pointer to beginning of file. (Same as rewind.)
fseek(fp, 0L, 1); Stay at the current position. (File pointer is not moved.)
fseek(fp, 0L, 2); Move file pointer past the last character of the file. (Go to
the end of file.)
fseek(fp, m, 0); Move file pointer to (m+1)th byte in the file.
fseek(fp, m, 1); Move file pointer forwards by m bytes.
fseek(fp, -m, 1); Move file pointer backwards by m bytes from the current
position.
fseek(fp, -m, 2); Move file pointer backwards by m bytes from the end.
(Positions the file pointer to the mth character from the
end.)
• When the operation is successful, fseek()
returns a 0 (zero).
• If we attempt to move the file pointer beyond
the file boundaries, an error occurs and fseek()
returns -1 (minus one).
• It is good practice to check whether an error
has occurred or not, before proceeding further.
66
fseek()…
67
/* A program that uses the functions ftell() and fseek() */
#include <stdio.h>
void main()
{
FILE *fp;
char c;
long n;
clrscr();
fp=fopen("RANDOM","w");
if(fp==NULL)
{
printf("nCannot create file.");
exit();
}
while((c=getchar())!=EOF)
fputc(c,fp);
printf("nNo. of characters entered=%ld",ftell(fp));
fclose(fp);
fp=fopen("RANDOM","r");
if(fp==NULL)
{
printf("nCannot create file.");
exit();
}
n=0L;
while(feof(fp)==0)
{
fseek(fp,n,0); //Position to (n+1)th character
printf("Position of %c is %ldn",fgetc(fp),ftell(fp));
n=n+5L;
}
putchar('n');
fseek(fp,-1L,2); /*Position to the last character*/
do
{
putchar(fgetc(fp));
}while(!fseek(fp,-2L,1));
fclose(fp);
getch();
}
68
Explanation
• A file called RANDOM is created with the
following contents:
Stored Character: A B C … Z
File Pointer Position: 0 1 2 … 25
• Then the file is read twice.
• At first, we read the contents of every fifth
position and print its value with its position on the
screen.
• At second, we read the contents of the file from
the end and print the same on screen.
• A book record consists of its title, author, pages
and price. Write a program to perform
following operations:
– Read the records of 13 books
– Create at least one structure pointer to display the
records of 13 books
– Store records of all 13 books in the file
“booklist.dat”
– Read only the information of 9 books from
“booklist.dat” skipping 2 books from first and 2
books from last and display in terminal
69
Problem
#define SIZE 13
void main()
{
struct book
{
char title[40];
char author[20];
int pages;
float price;
};
struct book b[SIZE];
int i;
float temp;
struct book *bp;
FILE *fp;
struct book bb[SIZE];
clrscr();
for(i=0;i<SIZE;i++)
{
printf("nEnter record of
book%d",i+1);
printf("nEnter title:t");
scanf("%s",b[i].title);
fflush(stdin);
printf("nEnter author:t");
scanf("%s",b[i].author);
printf("nEnter no. of
pages:t");
scanf("%d",&b[i].pages);
printf("nEnter price:t");
scanf("%f",&temp);
b[i].price=temp;
}
70
bp=b; //bp=&b[0];
for(i=0;i<SIZE;i++)
{
printf("nRecord of
Book%d",i+1);
printf("nTitle:%stAuthor:%s",(
bp+i)->title,(bp+i)->author);
printf("nNo. of
pages:%dtPrice:%.2fn",(bp+i)-
>pages,(bp+i)->price);
}
fp=fopen("booklist.dat","w+b");
if(fp==NULL)
{
puts("Cannot create file");
exit();
}
for(i=0;i<SIZE;i++)
fwrite(&b,sizeof(b),1,fp);
rewind(fp);
fseek(fp,sizeof(b)*2,0);
i=2;
printf("nReading from file:");
while(fread(&bb,sizeof(bb),1,fp)==1)
{
while(i<SIZE-2)
{
printf("nTitle:%stAuthor:%s",
bb[i].title, bb[i].author);
printf("nNo. of
pages:%dtPrice:%fn",
bb[i].pages, bb[i].price);
i++;
}
}
fclose(fp);
getch();
}
71
• A car record consists of its model,
manufacture_year and price. Write a program to
perform following operations:
– Read the records of 13 cars.
– Create at least one structure pointer to display
the records of 13 cars.
– Store records of all 13 cars in the file “c.mpg”.
– Read only the information of 5 cars from
“c.mpg”, skipping 8 cars from first and display
in standard output device.
72
PROBLEM
• Create a structure named employee having
empname, age and salary as its members. Read
these information for a number of employees (till
user wants) and write these information to a file
named employee.txt in C-drive. Finally, the
program should be able to search the information
of a particular employee by its empname from the
file.
73
PROBLEM
void main()
{
struct employee
{
char empname[20];
int age;
float salary;
};
struct employee e;
FILE *fp;
char name[20];
char ch='y';
int search=0;
fp=fopen("C:employee.txt","w+b");
clrscr();
do
{
printf("nEnter name, age and salary of
employee:");
scanf("%s %d %f", e.empname, &e.age,
&e.salary);
fwrite(&e,sizeof(e),1,fp);
fflush(stdin);
printf("nDo you want to information for
another employee(y for yes):");
scanf("%c", &ch);
}while(ch=='y');
rewind(fp);
printf(“ntEnter employee to be searched:t");
fflush(stdin);
gets(name);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(name, e.empname)==0)
{
search=1;
printf("nName:%s", e.empname);
printf("nAge:%d", e.age);
printf("nSalary:%.2f", e.salary);
}
}
if(search==0)
printf("nThere is no employee with name
%s", name);
fclose(fp);
getch();
}
74
• Write a program to open a file employee.txt
created in above program and edit/modify
the details of a particular employee.
75
PROBLEM
void main()
{
struct employee
{
char empname[20];
int age;
float salary;
};
struct employee e;
FILE *fp;
char name[20];
int search=0;
int record_count=0;
fp=fopen("C:employee.txt","rb+");
clrscr();
if(fp==NULL)
{
printf("Cannot open file");
exit();
}
printf("tEnter employee name to be modified:t");
gets(name);
while(fread(&e,sizeof(e),1,fp)==1)
{
if(strcmp(name, e.empname)==0)
{
search=1;
printf("n Old record is:");
printf("n Name:%s",e.empname);
printf("n Age:%d",e.age);
printf("n Salary:%.2f",e.salary);
printf("n Enter new record(name,age and
salary):");
scanf("%s %d %f", e.empname, &e.age,
&e.salary);
fseek(fp,sizeof(e)*record_count,0);
if(fwrite(&e,sizeof(e),1,fp)==1)
printf("nRecord modified!!!");
}
record_count++;
}
if(search==0)
printf("n There is no employee with name %s",
name);
fclose(fp);
getch();
}
76

More Related Content

What's hot

What's hot (20)

UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
 
C string
C stringC string
C string
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Structure in C
Structure in CStructure in C
Structure in C
 
Strings in C
Strings in CStrings in C
Strings in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Manipulators in c++
Manipulators in c++Manipulators in c++
Manipulators in c++
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Structure in c
Structure in cStructure in c
Structure in c
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Function in C
Function in CFunction in C
Function in C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 

Viewers also liked

Viewers also liked (12)

File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
Unit 4. Operators and Expression
Unit 4. Operators and Expression  Unit 4. Operators and Expression
Unit 4. Operators and Expression
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
File handling in c
File handling in c File handling in c
File handling in c
 
Unit 11. Graphics
Unit 11. GraphicsUnit 11. Graphics
Unit 11. Graphics
 
Unit 2. Elements of C
Unit 2. Elements of CUnit 2. Elements of C
Unit 2. Elements of C
 

Similar to File handling in C

Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 

Similar to File handling in C (20)

Unit5
Unit5Unit5
Unit5
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File management
File managementFile management
File management
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File management
File managementFile management
File management
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Engineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptxEngineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptx
 
Files in c
Files in cFiles in c
Files in c
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
6. chapter v
6. chapter v6. chapter v
6. chapter v
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
File Handling in C Programming for Beginners
File Handling in C Programming for BeginnersFile Handling in C Programming for Beginners
File Handling in C Programming for Beginners
 
Handout#01
Handout#01Handout#01
Handout#01
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
1file handling
1file handling1file handling
1file handling
 

More from Kamal Acharya

More from Kamal Acharya (20)

Programming the basic computer
Programming the basic computerProgramming the basic computer
Programming the basic computer
 
Computer Arithmetic
Computer ArithmeticComputer Arithmetic
Computer Arithmetic
 
Introduction to Computer Security
Introduction to Computer SecurityIntroduction to Computer Security
Introduction to Computer Security
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Web forms in php
Web forms in phpWeb forms in php
Web forms in php
 
Making decision and repeating in PHP
Making decision and repeating  in PHPMaking decision and repeating  in PHP
Making decision and repeating in PHP
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in php
 
Text and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHPText and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Capacity Planning of Data Warehousing
Capacity Planning of Data WarehousingCapacity Planning of Data Warehousing
Capacity Planning of Data Warehousing
 
Data Warehousing
Data WarehousingData Warehousing
Data Warehousing
 
Search Engines
Search EnginesSearch Engines
Search Engines
 
Web Mining
Web MiningWeb Mining
Web Mining
 
Information Privacy and Data Mining
Information Privacy and Data MiningInformation Privacy and Data Mining
Information Privacy and Data Mining
 
Cluster Analysis
Cluster AnalysisCluster Analysis
Cluster Analysis
 
Association Analysis in Data Mining
Association Analysis in Data MiningAssociation Analysis in Data Mining
Association Analysis in Data Mining
 
Classification techniques in data mining
Classification techniques in data miningClassification techniques in data mining
Classification techniques in data mining
 
Data Preprocessing
Data PreprocessingData Preprocessing
Data Preprocessing
 
Introduction to Data Mining and Data Warehousing
Introduction to Data Mining and Data WarehousingIntroduction to Data Mining and Data Warehousing
Introduction to Data Mining and Data Warehousing
 

Recently uploaded

Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
Avinash Rai
 

Recently uploaded (20)

How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Advances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdfAdvances in production technology of Grapes.pdf
Advances in production technology of Grapes.pdf
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 

File handling in C

  • 2. • Console oriented I/O functions use keyboard as input device and monitor as output device. • The I/O functions like printf(), scanf(), getchar(), putchar(), gets(), puts() • Problem: 1. Entire data is lost when either the program is terminated or the computer is turned off. 2. When the volume of data to be entered is large, it takes a lot of time to enter the data. 3. If user makes a mistake while entering data, whole data has to be re-entered. • Solution: File Background 2
  • 3. • File is a place on the disk (not memory) where a group of related data is stored. Also called data files. • The Data File allows us to store information permanently and to access and alter that information whenever necessary. Concept of file 3
  • 4. Classification of disk/file I/O functions Disk I/O Functions High-level Low-level Text Binary Formatted Unformatted UnformattedFormatted 4
  • 5. Function name Operation fopen() •Creates a new file for use •Opens an existing file for use fclose() •Closes a file which was opened for use fgetc() •Reads a character from a file fputc() •Writes a character to a file fprintf() •Writes a set of data values to a file fscanf() •Reads a set of data values from a file fseek() •Sets the position to a desired point in the file ftell() •Gives the current position in the file (in terms of bytes from the start) rewind() •Sets the position to the beginning of the file Some high-level I/O functions 5
  • 6. • The general format for declaring and opening a file is: FILE *fp; fp=fopen(“filename”, “mode”); • Here, the first statement declares the variable fp as a “pointer to the data type FILE”. • The second statement opens the file named filename with the purpose mode and the beginning address of the buffer area allocated for the file is stored by file pointer fp. • Note: Any no. of files can be opened and used at a time. Defining and Opening a file 6
  • 7. • There are mainly six modes: 1. “r” (i.e. read mode) 2. “w” (i.e. write mode) 3. “a” (i.e. append mode) 4. “r+” (i.e. read and write mode) 5. “w+” (i.e. write and read mode) 6. “a+” (i.e. append and read mode) File Opening Modes 7
  • 8. • The closing a file ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. • In cases where there is a limit to the no. of files that can be kept open simultaneously, closing of unwanted files help in opening the required ones. • Another instance where we have to close a file is when we want to reopen the same file in different mode. • The file is closed using library function fclose() as: fclose(fp); Closing a file 8
  • 9. • Once a file is opened, reading out of or writing to it is accomplished using the standard I/O functions. Library Functions for Reading/Writing from/to a File: File I/O Functions 9
  • 10. • Using string I/O functions fgets() and fputs(), data can be read from a file or written to a file in the form of array of characters. i. fgets(): is used to read string from file. Syntax: fgets(string, int_value, fp); Here, int_value denotes the no. of characters in the string. ii. fputs(): is used to write string to file. Syntax: fputs(string, fp); String Input/Output Functions 10
  • 11. #include<conio.h> #include<stdio.h> #include<stdlib.h> void main() { FILE *fp; clrscr(); fp=fopen("D:test.txt", "w"); if(fp==NULL) { printf("n Cannot create file."); exit(0); } else { printf("n File is created."); } fputs("I study CSIT", fp); fclose(fp); getch(); } 11
  • 12. #include<conio.h> #include<stdio.h> #include<stdlib.h> void main() { FILE *fp; char s[100]; clrscr(); fp=fopen("D:test.txt", "r"); if(fp==NULL) { printf("n Cannot open file."); exit(0); } else { printf("nFile is opened."); } fgets(s,19,fp); printf("n Text from file is:%s", s); fclose(fp); getch(); } 12
  • 13. #include<conio.h> #include<stdio.h> #include<stdlib.h> void main() { FILE *fp; clrscr(); fp=fopen("D:test.txt", "a"); if(fp==NULL) { printf("n Cannot open file."); exit(1); } else { printf("n File is opened."); } fputs(“in CAB", fp); fclose(fp); getch(); } 13
  • 14. void main() { FILE *fp; char filename[20]; clrscr(); printf("Enter filename:t"); gets(filename); fp=fopen(filename, "w"); if(fp==NULL) { printf("n Cannot create file."); exit(1); } else { printf("n File is created."); } getch(); } // If only filename is given, file is created in C:TCBIN otherwise file is created in the given path. 14 Naming a file
  • 15. • Using character I/O functions fgetc() and fputc(), data can be read from file or written onto file one character at a time. i. fgetc(): is used to read a character from a file. Syntax: char_variable=fgetc(fp); ii. fputc(): is used to write a character to a file. Syntax: fputc(‘character’or character_variable, fp); Character I/O Functions 15
  • 16. void main() { FILE *fp; char filename[20]; char c; clrscr(); printf("Enter filename:t"); gets(filename); fp=fopen(filename,"w"); if(fp==NULL) { printf("n Cannot create file."); exit(); } else printf("n File is created."); printf("n Enter your text until Enter key:n"); while((c=getchar())!='n') fputc(c,fp); fclose(fp); getch(); } 16
  • 17. void main() { FILE *fp; char filename[20]; char c; clrscr(); printf("Enter filename:t"); gets(filename); fp=fopen(filename, "r"); if(fp==NULL) { printf("n Cannot open file."); exit(); } printf("n The content of file is:n"); while((c=fgetc(fp))!=EOF) putchar(c); fclose(fp); getch(); } 17
  • 18. • EOF is a special character (an integer with ASCII value 26) that indicates that the end-of-file has been reached. This character can be generated from the keyboard by typing Ctrl+Z. • Defined in <stdio.h> • When we are creating a file, the special character EOF, is inserted after the last character of the file by the Operating System. • Caution: An attempt to read after EOF might either cause the program to terminate with an error or result in an infinite loop situation. 18 End-Of-File (EOF)
  • 19. void main() { FILE *fp; char filename[20]; char c; clrscr(); printf("Enter filename:t"); gets(filename); fp=fopen(filename,"a"); if(fp==NULL) { printf("n Cannot create or open file."); exit(); } printf("nEnter text to append to file %s:n", filename); while((c=getchar())!='n') fputc(c,fp); fclose(fp); getch(); } 19
  • 20. void main() { FILE *sfp,*dfp; char sfilename[20],dfilename[20]; char c; clrscr(); printf("Enter source filename:t"); gets(sfilename); printf("n Enter destination filename:t"); gets(dfilename); sfp=fopen(sfilename,"r"); if(sfp==NULL) { printf("nSource file can't be opened."); exit(); } dfp=fopen(dfilename, "w"); if(dfp==NULL) { printf("n Destination file cannot be created or opened."); exit(); } while((c=fgetc(sfp))!=EOF) fputc(c, dfp); printf("n Copied........"); fclose(dfp); fclose(sfp); getch(); } 20
  • 21. • Given a text file, create another text file deleting all the vowels (a, e, i, o, u). Question 21
  • 22. void main() { FILE *fp,*fpp; char c; fp=fopen("C:test.txt","r+"); clrscr(); if(fp==NULL) { printf("Cannot open file"); exit(); } fpp=fopen("C:hello.txt","w"); if(fpp==NULL) { printf("Cannot create file"); exit(); } while((c=fgetc(fp))!=EOF) { if((c!='a')&&(c!='e')&&(c!='i')&&( c!='o')&&(c!='u')) fputc(c, fpp); } fclose(fp); fclose(fpp); getch(); } 22
  • 23. • Using formatted I/O functions, fprintf() and fscanf(), numbers, characters or string can be read from file or written onto file according to our requirement format. i. fprintf(): is formatted output function which is used to write integer, float, char or string value to a file. Syntax: fprintf(fp, “control_string”, list_of_variables); ii. fscanf(): is formatted input function which is used to read integer, float, char or string value from a file. Syntax: fscanf(fp, “control_string”, &list_of_variables); 23 Formatted I/O Functions
  • 24. void main() { FILE *fp; char name[20]; int roll; char address[20]; float marks; clrscr(); fp=fopen("C:student.txt", "w"); if(fp==NULL) { printf("n File cannot be created or opened."); exit(); } 24
  • 25. printf("n Enter name of student:t"); gets(name); printf("n Enter roll number of %s:t", name); scanf("%d", &roll); fflush(stdin); printf("n Enter address of %s:t", name); gets(address); printf("n Enter marks of %s:t", name); scanf("%f", &marks); printf("n Now writing data to file..."); fprintf(fp, "Name=%sn Roll=%dn Address=%sn Marks=%.2f", name, roll, address, marks); printf("n Completed"); fclose(fp); getch(); } 25
  • 26. • Here, after providing name of student, we would hit enter key……No Problem……and then we provide roll of student……and hit the enter key again…...Problem…... • At this time the enter key which is in the keyboard buffer is read by the gets()/scanf() function for address (as enter key is a character, n), so that we are able to fill only the marks. • To avoid this problem, we use the function fflush(). • It is designed to remove or flush out any data remaining in the buffer. 26 Use of fflush()
  • 27. • Define a structure for Vehicle Owner having data members name, address, telephone number, vehicle number and license number. Take the data for ten owners, write them in file “Own.txt”. Read the data from the file and display them. Question 27
  • 28. struct vehicle_owner { char name[20]; char address[20]; long int phone_no; int vehicle_no; int license_no; }; void main() { FILE *fp; struct vehicle_owner vehicle[10], v[10]; int i; clrscr(); fp=fopen("C:Own.txt","w"); if(fp==NULL) { printf("nCannot create file."); exit(); } 28
  • 29. for(i=0;i<SIZE;i++) { printf("n Enter information about vehicle owner %d",i+1); printf("n Enter name :t"); gets(vehicle[i].name); printf("n Enter address:t"); gets(vehicle[i].address); printf("n Enter telephone no:t"); scanf("%ld", &vehicle[i].phone_no); printf("n Enter vehicle no:t"); scanf("%d", &vehicle[i].vehicle_no); printf("n Enter license no:t"); scanf("%d", &vehicle[i].license_no); fprintf(fp,"%st%st%ldt%dt%dn", vehicle[i].name, vehicle[i].address, vehicle[i].phone_no, vehicle[i].vehicle_no, vehicle[i].license_no); fflush(stdin); } 29
  • 30. fclose(fp); fp=fopen("C:Own.txt","r"); for(i=0;i<10;i++) { fscanf(fp,"%s %s %ld %d %d",&v[i].name,&v[i].address,&v[i].phone_no,&v[i].vehicle_no,&v[i].license_ no); printf("%st%st%ldt%dt%dn",v[i].name,v[i].address,v[i].phone_no,v[i].vehicl e_no,v[i].license_no); } fclose(fp); getch(); }
  • 31. • Given a text file, create another text file deleting the following words “three”, “bad”, and “time”. Problem 31
  • 32. #include <stdio.h> void main() { FILE *fp,*fpp; char c[10]; fp=fopen("C:test.txt",“r"); clrscr(); if(fp==NULL) { printf("Cannot open file"); exit(); } fpp=fopen("C:hello.txt","w"); if(fpp==NULL) { printf("Cannot create file"); exit(); } while(fscanf(fp,"%s",c)!=EOF) { if((strcmp(c,"three")!=0)&&(strcmp(c,"bad")!=0)&&(strcmp(c,"time")!=0)) { fprintf(fpp,"%s ",c); } } fclose(fp); fclose(fpp); getch(); } 32
  • 33. • Some text file is given, create another text file replacing the following words “Ram” to “Hari”, “Sita” to “Gita”, and “Govinda” to “Shiva”. Problem 33
  • 34. #include <stdio.h> void main() { FILE *fp,*fpp; char c[10]; fp=fopen("C:test.txt","r"); clrscr(); if(fp==NULL) { printf("Cannot open file"); exit(); } fpp=fopen("C:hello.txt","w"); if(fpp==NULL) { printf("Cannot create file"); exit(); } while(fscanf(fp,"%s",c)!=EOF) { if(strcmp(c, "Ram")==0) fprintf(fpp, "Hari ",c); else if(strcmp(c, "Sita")==0) fprintf(fpp,"Gita",c); else if(strcmp(c, "Govinda")==0) fprintf(fpp, "Shiva",c); else fprintf(fpp,"%s ",c); } fclose(fp); fclose(fpp); getch(); } 34
  • 35. • Create a program to create a data file and write the integers from 1 to 20 to this file and then read the numbers from the file to display the squares of the stored numbers. 35 Question
  • 36. #include <stdio.h> void main() { FILE *fp; register unsigned int i; unsigned filedata; clrscr(); fp=fopen("C:data.txt","w"); if(fp==NULL) { printf("nCannot create data file."); exit(); } for(i=1;i<21;i++) { fprintf(fp,"%ut",i); } fclose(fp); fp=fopen("C:data.txt","r"); printf("nThe squares of the stored numbers are:t"); for(i=1;i<21;i++) { fscanf(fp,"%u",&filedata); filedata=filedata*filedata; printf("%ut", filedata); } getch(); } 36
  • 37. • A file named DATA contains a series of integer numbers. Code a program to read these numbers and then write all odd numbers to a file to be called ODD and all even numbers to a file to be called EVEN. 37 Question
  • 38. #include <stdio.h> void main() { FILE *fpdata; FILE *fpodd; FILE *fpeven; int i,n; int num; clrscr(); printf("nHow many integers you want in data file?:t"); scanf("%d",&n); printf("nEnter %d integers:t",n); fpdata=fopen("C:DATA.txt","w"); for(i=0;i<n;i++) { scanf("%d",&num); fprintf(fpdata,"%dn",num); } fclose(fpdata); fpdata=fopen("C:DATA.txt","r"); fpodd=fopen("C:ODD.txt","w"); fpeven=fopen("C:EVEN.txt","w"); 38
  • 40. • Trying to read beyond the end-of-file mark. • Trying to use a file that has not been opened. • Trying to perform an operation on a file, when the file is opened for another type of operation. • Opening a file with an invalid filename. 40 Error situations during I/O operations
  • 41. • I/O errors can be detected using two status-inquiry library functions: feof() and ferror(). • feof(): It is used to test for an end-of-file condition. It takes a FILE pointer as its only argument and returns a nonzero integer value if all of the data from the specified file has been read, and returns zero otherwise. If fp is a pointer to a file that has just been opened for reading, then the statement if(feof(fp)) printf(“End of data”); would display the message “End of data” on reaching the end-of-file condition. 41 Error handling functions
  • 42. • ferror(): This function reports the status of the file indicated. It takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing. It returns zero otherwise. So the statement if(ferror(fp)!=0) printf(“An error has occurred”); would print the error message, if the reading is not successful. 42 Error handling functions…
  • 43. void main() { FILE *fp1; char *filename; int i, num; clrscr(); fp1=fopen("C:test.txt", "w"); for(i=10;i<=100;i += 10) { fprintf(fp1,"%dt", i); } fclose(fp1); printf("n Enter filename:t"); //Type C:test.txt open_file: scanf("%s", filename); 43
  • 44. if((fp1=fopen(filename,"r"))==NULL) { printf("nAn error occured while opening the file."); printf("nType filename again:t"); goto open_file; } else for(i=1;i<=20;i++) { fscanf(fp1,"%d", &num); if(feof(fp1)) { printf("nRan out of data."); break; } else printf("%dn", num); } fclose(fp1); getch(); } 44
  • 45. void main() { FILE *fp; int num; clrscr(); fp = fopen("DUMMY.FIL", "w"); /* force an error condition by attempting to read */ fscanf(fp,"%d", &num); if (ferror(fp)!=0) { printf("Error reading from DUMMY.FILn"); } fclose(fp); getch(); } 45
  • 46. • The binary files organize data into blocks containing contiguous bytes of information. • In binary file, the opening mode of text file is appended by a character b i.e. i. “r” is replaced by “rb” ii. “w” is replaced by “wb” iii. “a” is replaced by “ab” iv. “r+” is replaced by “r+b” v. “w+” is replaced by “w+b” vi. “a+” is replaced by “a+b” 46 Binary Data Files Note: For text mode we can write “rt” in place of “r”, “wt” in place of “w”and so on. However, it is unnessary because default mode is text mode
  • 47. void main() { FILE *fp; char c; clrscr(); fp=fopen("C:test.txt","w+b"); if(fp==NULL) { printf("nCannot create file."); exit(); } fputs("I study B.Sc. CSIT", fp); fclose(fp); getch(); } 47
  • 48. • Analyze with 3 factors: I. How newlines (n) are stored? II. How end-of-file is indicated? III. How numbers are stored in the file? 48 So, what’s the difference between text mode and binary mode and which mode to use???
  • 49. /*Count no. of characters, spaces, and newlines in a file*/ void main() { FILE *fp; char text[100]; char c; int noc=0,nos=0,nol=0; fp=fopen("C:poem.txt", "r"); if(fp==NULL) { printf("nCannot create or open file."); exit(); } while(1) { c=fgetc(fp); if(c==EOF) break; noc++; if(c==' ') nos++; if(c=='n') nol++; } fclose(fp); printf("n No. of characters:%d", noc); printf("n No. of spaces:%d", nos); printf("n No. of lines:%d", nol); getch(); } 49
  • 50. Johnny Johnny Yes Papa Eating Sugar No Papa Telling Lies No Papa Open Your Mouth hahaha 50 The poem.txt file contains: So output is: No. of characters=87 No. of spaces=8 No. of lines=7 which is correct. Now, go to DOS shell and use the DIR command in C-drive to view the no. of characters (bytes) that the file poem.txt occupies which is 94.
  • 51. • In text mode, a newline character is converted into the carriage return-linefeed combination before being written to disk. • Likewise, the carriage return-linefeed combination on the disk is converted back into a newline when the file is read by a C program. • However, if a file is opened in binary mode, as opposed to text mode, these conversions do not take place. • In binary mode, each end of line is signified by a carriage return-linefeed combination and is counted as two characters in binary mode (similar to DIR command in DOS). 51 First factor
  • 52. 52 /*Count no. of characters, spaces, and newlines in a file*/ void main() { FILE *fp; char text[100]; char c; int noc=0,nos=0,nol=0; fp=fopen("C:poem.txt", "rb"); if(fp==NULL) { printf("nCannot create or open file."); exit(); } while(1) { c=fgetc(fp); if(c==EOF) break; noc++; if(c==' ') nos++; if(c=='n') nol++; } fclose(fp); printf("n No. of characters:%d", noc); printf("n No. of spaces:%d", nos); printf("n No. of lines:%d", nol); getch(); }
  • 53. • In text mode, a special character EOF whose ASCII value is 26 is inserted after the last character in the file to mark the end of file. • However, there is no such special character present in the binary mode files to mark the end of file. • The binary mode files keep track of the end of file from the number of characters present in the directory entry of the file. 53 Second Factor
  • 54. • In text mode, the text and numbers are stored as string of characters such that the number 12345 will occupy 5 bytes (1 byte/character). • Similarly 1234.56 occupies 7 bytes on disk in text mode. • However, in binary mode the numbers are stored in the same way as they are stored in RAM so that the number 12345 occupies only 2 bytes and 1234.56 occupies only 4 bytes on disk in binary mode. • Therefore, when large amount of numerical data is to be stored onto disk, binary mode is suitable by using functions fread() and fwrite() instead of fprintf() and fscanf(). 54 Third Factor
  • 55. • The character I/O and string I/O functions allow reading/writing of character data only, while the formatted I/O functions allow reading/writing of character data and numeric data both. • Problem: Numbers are always stored as a sequence of characters using these I/O functions (irrespective of whether text mode or binary mode is being used), so that they occupy a lot of disk space. 55 Record I/O……Background Problems
  • 56. • Another Problem: There is no direct way to read and write complex data types such as arrays and structures. Arrays and structures are handled by writing/reading one element at a time or using loops, but this approach is inefficient. • Example: 56 #include <stdio.h> void main() { FILE *fp; char another='Y'; struct emp { char name[40]; int age; float salary; }; struct emp e; fp=fopen("c:emp.dat","wb"); if(fp==NULL) { puts("Cannot create or open file"); exit(); } while(another=='Y') { printf("nEnter name, age and basic salary"); scanf("%s %d %f",e.name,&e.age,&e.salary); fprintf(fp,"%st%dt%f",e.name,e.age,e.salary); printf("nAdd another record(Y/N):t"); fflush(stdin); another=getche(); } fclose(fp); getch(); } Here, if the no. of fields in the structure increase (say by adding address, house rent allowance etc.), writing structures using fprintf(), or reading them using fscanf(), becomes quite clumsy.
  • 57. • Defined in <stdio.h> • fwrite(): is used for record output. Syntax: fwrite(&p, size_of_array_or_structure, no._of_array_or_structure, fp); • fread(): is used for record input. Syntax: fread (&p, size_of_array_or_structure, no._of_array_or_structure, fp); 57 Record Input/Output Functions
  • 58. #include <stdio.h> void main() { FILE *fp; char another='Y'; struct emp { char name[40]; int age; float salary; }; struct emp e; clrscr(); fp=fopen("c:emp.dat","wb"); if(fp==NULL) { puts("Cannot create or open file"); exit(); } while(another=='Y'||another=='y') { printf("n Enter name, age and basic salary:"); scanf("%s %d %f", e.name, &e.age, &e.salary); fwrite(&e,sizeof(e),1,fp); printf("n Add another record(Y/N):t"); fflush(stdin); another=getche(); } fclose(fp); fp=fopen("c:emp.dat","rb"); if(fp==NULL) { puts("Cannot create or open file"); exit(); } while(fread(&e,sizeof(e),1,fp)==1) { printf("n%st%dt%f", e.name, e.age, e.salary); } fclose(fp); getch(); } 58
  • 59. #include <stdio.h> void main() { FILE *fp; struct emp { char name[40]; int age; float salary; }; struct emp e[2],ee[2]; int i; float temp; clrscr(); fp=fopen("c:employee.dat","wb"); if(fp==NULL) { puts("Cannot create or open file"); exit(); } for(i=0;i<2;i++) { printf("nEnter name, age and basic salary:"); scanf("%s %d %f",e[i].name,&e[i].age,&temp); e[i].salary=temp; fflush(stdin); } fwrite(&e,sizeof(e),2,fp); fclose(fp); fp=fopen("c:employee.dat","rb"); if(fp==NULL) { puts("Cannot open file"); exit(); } fread(&ee,sizeof(ee),2,fp) for(i=0;i<2;i++) printf("n%st%dt%.2f", ee[i].name, ee[i].age, ee[i].salary); fclose(fp); getch(); } 59
  • 60. • Till now, reading and writing data from/to a file has been done sequentially. • But we may need to access a particular data item placed in any location without starting from the beginning. • This is called random access or direct access. 60 Random Access in a File (Direct Access)
  • 61. • A file pointer is a pointer to a particular byte in a file. • While opening a file in write mode, the file pointer is at the beginning of the file, and whenever we write to a file, the file pointer moves to the end of the data items written so that writing can continue from that point. • While opening a file in read mode, the file pointer is at the beginning of the file, and whenever we read from a file, the file pointer moves to the beginning of the next data item so that reading cam continue from that point. • While opening a file in append mode, the file pointer is at the end of the existing file, so that new data items can be written from there onwards. • If we are able to move the file pointer according as our need, then any data item can be read from a file or written onto a file randomly…………Random Access 61 Use of file pointer for random access…
  • 62. 1. ftell(): This function takes a file pointer as argument and returns a number of type long, that indicates the current position of the file pointer within the file. This function is useful in saving the current position of a file, which can be used later in the program. Syntax n = ftell(fp); Here, n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written). 62 Functions used in random access
  • 63. 2. rewind():This function takes a file pointer as argument and resets the current position of the file pointer to the start of the file. Syntax: rewind(fp);  What these statements do?: rewind(fp); n=ftell(fp); • Here, n would be assigned 0, because file position has been set to the start of the file by rewind(). • Note: The first byte in the file is numbered as 0, second as 1, and so on. 63 Functions used in random access
  • 64. 3. fseek(): This function is used to move the file pointer to a desired position within a file. Syntax fseek(fp, offset, position); where fp is a file pointer, offset is a number or variable data type long, and position is an integer number • The offset specifies the number of positions (bytes) to be moved from the location specified by position. • The position can have one of the following 3 values: 64 Functions used in random access… Value Meaning 0 Beginning of file 1 Current position 2 End of file
  • 65. • The offset may be positive, meaning move forwards, or negative, meaning move backwards. • Examples: 65 fseek()… Statement Meaning fseek(fp, 0L, 0); Move file pointer to beginning of file. (Same as rewind.) fseek(fp, 0L, 1); Stay at the current position. (File pointer is not moved.) fseek(fp, 0L, 2); Move file pointer past the last character of the file. (Go to the end of file.) fseek(fp, m, 0); Move file pointer to (m+1)th byte in the file. fseek(fp, m, 1); Move file pointer forwards by m bytes. fseek(fp, -m, 1); Move file pointer backwards by m bytes from the current position. fseek(fp, -m, 2); Move file pointer backwards by m bytes from the end. (Positions the file pointer to the mth character from the end.)
  • 66. • When the operation is successful, fseek() returns a 0 (zero). • If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek() returns -1 (minus one). • It is good practice to check whether an error has occurred or not, before proceeding further. 66 fseek()…
  • 67. 67 /* A program that uses the functions ftell() and fseek() */ #include <stdio.h> void main() { FILE *fp; char c; long n; clrscr(); fp=fopen("RANDOM","w"); if(fp==NULL) { printf("nCannot create file."); exit(); } while((c=getchar())!=EOF) fputc(c,fp); printf("nNo. of characters entered=%ld",ftell(fp)); fclose(fp); fp=fopen("RANDOM","r"); if(fp==NULL) { printf("nCannot create file."); exit(); } n=0L; while(feof(fp)==0) { fseek(fp,n,0); //Position to (n+1)th character printf("Position of %c is %ldn",fgetc(fp),ftell(fp)); n=n+5L; } putchar('n'); fseek(fp,-1L,2); /*Position to the last character*/ do { putchar(fgetc(fp)); }while(!fseek(fp,-2L,1)); fclose(fp); getch(); }
  • 68. 68 Explanation • A file called RANDOM is created with the following contents: Stored Character: A B C … Z File Pointer Position: 0 1 2 … 25 • Then the file is read twice. • At first, we read the contents of every fifth position and print its value with its position on the screen. • At second, we read the contents of the file from the end and print the same on screen.
  • 69. • A book record consists of its title, author, pages and price. Write a program to perform following operations: – Read the records of 13 books – Create at least one structure pointer to display the records of 13 books – Store records of all 13 books in the file “booklist.dat” – Read only the information of 9 books from “booklist.dat” skipping 2 books from first and 2 books from last and display in terminal 69 Problem
  • 70. #define SIZE 13 void main() { struct book { char title[40]; char author[20]; int pages; float price; }; struct book b[SIZE]; int i; float temp; struct book *bp; FILE *fp; struct book bb[SIZE]; clrscr(); for(i=0;i<SIZE;i++) { printf("nEnter record of book%d",i+1); printf("nEnter title:t"); scanf("%s",b[i].title); fflush(stdin); printf("nEnter author:t"); scanf("%s",b[i].author); printf("nEnter no. of pages:t"); scanf("%d",&b[i].pages); printf("nEnter price:t"); scanf("%f",&temp); b[i].price=temp; } 70
  • 71. bp=b; //bp=&b[0]; for(i=0;i<SIZE;i++) { printf("nRecord of Book%d",i+1); printf("nTitle:%stAuthor:%s",( bp+i)->title,(bp+i)->author); printf("nNo. of pages:%dtPrice:%.2fn",(bp+i)- >pages,(bp+i)->price); } fp=fopen("booklist.dat","w+b"); if(fp==NULL) { puts("Cannot create file"); exit(); } for(i=0;i<SIZE;i++) fwrite(&b,sizeof(b),1,fp); rewind(fp); fseek(fp,sizeof(b)*2,0); i=2; printf("nReading from file:"); while(fread(&bb,sizeof(bb),1,fp)==1) { while(i<SIZE-2) { printf("nTitle:%stAuthor:%s", bb[i].title, bb[i].author); printf("nNo. of pages:%dtPrice:%fn", bb[i].pages, bb[i].price); i++; } } fclose(fp); getch(); } 71
  • 72. • A car record consists of its model, manufacture_year and price. Write a program to perform following operations: – Read the records of 13 cars. – Create at least one structure pointer to display the records of 13 cars. – Store records of all 13 cars in the file “c.mpg”. – Read only the information of 5 cars from “c.mpg”, skipping 8 cars from first and display in standard output device. 72 PROBLEM
  • 73. • Create a structure named employee having empname, age and salary as its members. Read these information for a number of employees (till user wants) and write these information to a file named employee.txt in C-drive. Finally, the program should be able to search the information of a particular employee by its empname from the file. 73 PROBLEM
  • 74. void main() { struct employee { char empname[20]; int age; float salary; }; struct employee e; FILE *fp; char name[20]; char ch='y'; int search=0; fp=fopen("C:employee.txt","w+b"); clrscr(); do { printf("nEnter name, age and salary of employee:"); scanf("%s %d %f", e.empname, &e.age, &e.salary); fwrite(&e,sizeof(e),1,fp); fflush(stdin); printf("nDo you want to information for another employee(y for yes):"); scanf("%c", &ch); }while(ch=='y'); rewind(fp); printf(“ntEnter employee to be searched:t"); fflush(stdin); gets(name); while(fread(&e,sizeof(e),1,fp)==1) { if(strcmp(name, e.empname)==0) { search=1; printf("nName:%s", e.empname); printf("nAge:%d", e.age); printf("nSalary:%.2f", e.salary); } } if(search==0) printf("nThere is no employee with name %s", name); fclose(fp); getch(); } 74
  • 75. • Write a program to open a file employee.txt created in above program and edit/modify the details of a particular employee. 75 PROBLEM
  • 76. void main() { struct employee { char empname[20]; int age; float salary; }; struct employee e; FILE *fp; char name[20]; int search=0; int record_count=0; fp=fopen("C:employee.txt","rb+"); clrscr(); if(fp==NULL) { printf("Cannot open file"); exit(); } printf("tEnter employee name to be modified:t"); gets(name); while(fread(&e,sizeof(e),1,fp)==1) { if(strcmp(name, e.empname)==0) { search=1; printf("n Old record is:"); printf("n Name:%s",e.empname); printf("n Age:%d",e.age); printf("n Salary:%.2f",e.salary); printf("n Enter new record(name,age and salary):"); scanf("%s %d %f", e.empname, &e.age, &e.salary); fseek(fp,sizeof(e)*record_count,0); if(fwrite(&e,sizeof(e),1,fp)==1) printf("nRecord modified!!!"); } record_count++; } if(search==0) printf("n There is no employee with name %s", name); fclose(fp); getch(); } 76