0% found this document useful (0 votes)
2 views90 pages

Files Handling

The document discusses the concept of file I/O in C programming, highlighting the limitations of console-oriented I/O functions and introducing file operations for permanent data storage. It details the types of files, file opening modes, and various high-level I/O functions such as fopen(), fclose(), fgetc(), and fputc(). Additionally, it provides examples of file handling operations including creating, reading, writing, and appending to files.

Uploaded by

yamkumar077a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views90 pages

Files Handling

The document discusses the concept of file I/O in C programming, highlighting the limitations of console-oriented I/O functions and introducing file operations for permanent data storage. It details the types of files, file opening modes, and various high-level I/O functions such as fopen(), fclose(), fgetc(), and fputc(). Additionally, it provides examples of file handling operations including creating, reading, writing, and appending to files.

Uploaded by

yamkumar077a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 90

Background

 The I/O functions like printf(), scanf(), getchar(), putchar(),


gets(), puts(), which we have used till now are called console
oriented I/O functions.
 Console oriented I/O functions use keyboard as input device
and monitor as output device.
 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
1
Concept of file
 A 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.
 To perform basic file operations, C supports a number of
functions, which include functions for:
◦ naming a file,
◦ opening a file,
◦ reading data from file,
◦ writing data to a file, and
◦ closing a file

2
Concept of file…
 Basically, there are two kinds of data files:
◦ high-level or stream oriented or standard
◦ low-level or system-oriented
 In high-level data files, the available library functions (in the C’s
standard I/O library) do their own buffer management whereas in
low-level data files (using UNIX system calls) a programmer is
required to do buffer management explicitly.
 The high-level data files are further subdivided into two: text files
and binary files.
 The text files consist of consecutive characters and these
characters can be interpreted as individual data items whereas the
binary files organize data into blocks containing contiguous bytes
of information.
 There are a number of formatted and unformatted functions in C
for both text and binary files.
3
Classification of disk/file I/O functions
Disk I/O
Functions

High-level Low-level

Text Binary

Formatte Unformatte Formatte Unformatte


d d d d

4
Some high-level I/O
functions
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

5
Defining and Opening a file
 If we want to store data in a file in the disk, we must
specify certain things about the file to the operating
system. They are:
1. Filename
2. Data Structure
3. Purpose
 Filename is a string of characters that make up a valid
filename for the operating system.
 The filename consists of two parts, a primary name and

an optional dot with the extension.


 Examples: input.data, data, student.txt, prog.c, etc.

6
Defining and Opening a
file…
 Data structure of a file is defined as FILE in <stdio.h>.
 So that, all files should be declared as FILE before
they are used.
 FILE is a defined data type.
 The purpose specifies what we want to do with the file.

For example, we may want to write data to the file or


read the already existing data.
 But before a program can write to a file or read from a

file, the program must open it first.


 Opening a file establishes a communication link

between the program and the operating system.

7
Defining and Opening a
file…
 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.

8
File Opening Modes
 The file opening mode specifies the way in which a file
should be opened (i.e. for reading, writing or both,
appending at the end of the file, overwriting the file,
etc.).
 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)

9
File Opening Modes…
 “r”: This mode opens an existing file for reading only
purpose. If file exists, then the file is loaded into memory
and a pointer that points to the first character in the file is
assigned to the file pointer. If file does not exist, then it
returns NULL. The possible operation is – reading from
the file only.
 “w”: This mode opens a file for writing only purpose. If
file exists, then the contents of the file are overwritten
(content is deleted first and then written). If file does not
exist, a new file is created. It returns NULL, if it is
unable to open the file in write mode. The possible
operation is – writing to the file only.
10
File Opening Modes…
 “a”: This mode opens an existing file for appending purpose
(i.e. adding new information at the end of file). If file exists,
then the file is loaded into memory and a pointer that points to
the last character of the file is assigned to the file pointer. If file
does not exist, a new file is created. It returns NULL, if it is
unable to open the file in append mode. The possible operation
is – adding new contents at the end of file.
 “r+”: This mode opens an existing file for reading and writing
purpose. If file exists, then the file is loaded into memory and a
pointer that points to the first character in the file is assigned to
the file pointer. If file does not exist, then it returns NULL. The
possible operations are – reading existing contents, writing new
contents and modifying existing contents of the file.
11
File Opening Modes…
 “w+”: This mode opens a file for reading and writing purpose.
If file exists, then the contents of the file are deleted. If file does
not exist, a new file is created. It returns NULL, if it is unable to
open the file in this mode. The possible operations are – writing
new contents, reading them back and modifying existing
contents of the file.
 “a+”: This mode opens an existing file for reading and
appending purpose. If file exists, then the file is loaded into
memory and a pointer that points to the first character in the file
is assigned to the file pointer. If file does not exist, then a new
file is created. The possible operations are – reading existing
contents, appending new contents to end of file but it cannot
modify existing contents of the file.
12
Closing a file
 A file must be closed as soon as all operations on it have been
completed.
 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.
 It also prevents any accidental misuse of the file.
 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);

13
Library Functions for Reading/Writing
from/to a File: File I/O Functions
 Once a file is opened, reading out of or writing to it is
accomplished using the standard I/O functions.

14
String Input/Output Functions
 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. fputs(): is used to write string to file.
Syntax: fputs(string, fp);

ii. 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.

15
/* Program to create a file named test.txt
and write some text “I study B.Sc. CSIT” to
the file. */
#include <stdio.h> else
void main() {
{ printf("\n File is created.");
FILE *fp; }
fputs("I study B.Sc. CSIT", fp);
clrscr();
fclose(fp);
fp=fopen("C:\\test.txt", "w"); getch();
if(fp==NULL) }
{
printf("\n Cannot create
file.");
exit();
}

16
Why the condition
if(fp==NULL)???
 We know that whenever a file is opened using fopen()
function, a file pointer is returned.
 If the file cannot be opened for some reason, then the

function fopen() returns a NULL pointer which is


defined in <stdio.h>
 So this facility can be used to test whether a file has

been opened or not.

17
/* Program to open the file named test.txt,
read its content and display it to screen */

#include <stdio.h> else


void main() {
{ printf("\nFile is opened.");
FILE *fp; }
char s[100]; fgets(s,19,fp);
clrscr(); printf("\n Text from file is:
fp=fopen(“D:test.txt", "r"); %s", s);
if(fp==NULL) fclose(fp);
{ getch();
printf("\n Cannot open }
file."); 1/2/3/5/6/7/9/10/11/12/13/14/15
exit(); /16/17/18/19/20/21/22/23/24/
} 25/26/27/28/30/31/32/33/35/
36/37/39/40/41/42/45/47/48
18
/* Program to open the file named test.txt
and add to it the text “@TU” */

#include <stdio.h> else


void main() {
{ printf("\n File is opened.");
FILE *fp; }
clrscr(); fputs("@TU", fp);
fp=fopen(“D:test.txt", "a"); fclose(fp);
if(fp==NULL) getch();
{ }
printf("\n Cannot open
file.");
exit(1);
}

19
Naming a file
#include <stdio.h>
void main() if(fp==NULL)
{ {
FILE *fp; printf("\n Cannot create
char filename[20]; file.");
clrscr(); exit(1);
printf("Enter filename:\t"); }
gets(filename); else
fp=fopen(filename, "w"); {
printf("\n File is created.");
}
getch();
}
// If only filename is given, file is
created in C:\TC\BIN otherwise
file is created in the given path. 20
Character I/O Functions
 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);

21
/* Program to create a file and write some text to it one
character at a time using fputc() function until user hits the
enter key*/
#include <stdio.h>
void main() if(fp==NULL)
{ {
FILE *fp; printf("\n Cannot create file.");
char filename[20]; exit();
char c; }
clrscr(); else
printf("Enter filename:\t"); printf("\n File is created.");
gets(filename); printf("\n Enter your text until
fp=fopen(filename,"w"); Enter key:\n");
while((c=getchar())!='\n')
fputc(c,fp);
fclose(fp);
getch();
}
22
/* Program to open a file, read its content one
character at a time using fgetc() function and display
it to screen*/
#include <stdio.h> printf("\n Cannot open
void main() file.");
{ exit();
FILE *fp; }
char filename[20];
char c;
clrscr(); printf("\n The content of
printf("Enter filename:\ file is:\n");
t"); while((c=fgetc(fp))!=EOF)
//EOF=>end-of-file
putchar(c);
gets(filename);
fp=fopen(filename, "r"); fclose(fp);
if(fp==NULL) getch();
{ }
23
End-Of-File (EOF)
 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.
 Thus, the last point of file is detected using EOF while reading
data from file.
 It’s necessity arises from the fact that we may not know in
advance up to where we have data.
 Caution: An attempt to read after EOF might either cause the
program to terminate with an error or result in an infinite loop
situation.

24
/* Program to append some text to a file by reading filename
from user*/
#include <stdio.h>
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();
}

25
/* Program to open a file and copy all its content to another file*/
#include <stdio.h> exit();
void main() }
{ dfp=fopen(dfilename, "w");
FILE *sfp,*dfp; if(dfp==NULL)
char sfilename[20],dfilename[20]; {
char c; printf("\n Destination file cannot
clrscr(); be created or opened.");
printf("Enter source filename:\t"); exit();
gets(sfilename); }
printf("\n Enter destination while((c=fgetc(sfp))!=EOF)
filename:\t"); fputc(c, dfp);
gets(dfilename); printf("\n Copied........");
sfp=fopen(sfilename,"r"); fclose(dfp);
if(sfp==NULL) fclose(sfp);
{ getch();
printf("\nSource file can't be }
opened.");

26
Formatted I/O Functions
 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);

27
/* Program to create a file named student.txt and write name,
roll, address and marks of a student to this file*/
#include <stdio.h>
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();
}

28
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=%s\n Roll=%d\n Address=%s\n Marks=%.2f",
name, roll, address, marks);
printf("\n Completed");
fclose(fp);
getch();
}

29
Use of fflush()
 There is a peculiarity of scanf() and/or gets().
 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.
 The argument to fflush() must be the buffer which we want to flush
out.
 Here, we have used stdin, which means buffer related with standard
input device, i.e. keyboard.

30
Use of fflush()…
 The fflush() function writes any buffered data to the
specified file stream. When you write data to a file
(with a function such as fprintf()), it is actually placed
in a memory buffer. The data is only actually written to
the file when the buffer is full, the file stream is closed
or when fflush() is called.

31
Question
 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.

32
#include <stdio.h>
#define SIZE 10
void main()
{
FILE *fp;
struct vehicle_owner
{
char name[20];
char address[20];
long int phone_no;
int vehicle_no;
int license_no;
};
struct vehicle_owner vehicle[SIZE], v[SIZE];
int i;
clrscr();
fp=fopen("C:\\Own.txt","w");
if(fp==NULL)
{
printf("\nCannot create file.");
exit();
}

33
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,"%s\t%s\t%ld\t%d\t%d\n", vehicle[i].name, vehicle[i].address, vehicle[i].phone_no,
vehicle[i].vehicle_no, vehicle[i].license_no);
fflush(stdin);
}
fclose(fp);
fp=fopen("C:\\Own.txt","r");
for(i=0;i<SIZE;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("%s\t%s\t%ld\t%d\t%d\n",v[i].name,v[i].address,v[i].phone_no,v[i].vehicle_no,v[i].license_no);
}
fclose(fp);
getch();
}

34
Error situations during I/O
operations
 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.

35
Error handling functions
 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.

36
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.

37
#include <stdio.h>
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,"%d\t", i);
}
fclose(fp1);
printf("\n Enter filename:\t"); //Type C:\test.txt
open_file:
scanf("%s", filename);
38
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("%d\n", num);
}
fclose(fp1);
getch();
}

39
#include <stdio.h>
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.FIL\n");
}
fclose(fp);
getch();
}
40
Random Access in a File (Direct
Access)
 Till now, reading and writing data from/to a file has
been done sequentially.
 While reading data from a file, the data items are read

from the beginning of the file in sequence until the end


of file.
 Also, while writing data to a file, the data items are

placed one after the other in a sequence.


 This is called sequential access.
 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.

41
Use of file pointer for random 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.
 So, 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
42
Functions used in 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).

43
Functions used in random access
2. rewind(): Do you remember that one way of positioning
the file pointer to the beginning of the file is to close the
file and then reopen it??? The rewind() function can do
this without closing the file. 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.

44
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 Value
have Meaning
one of the following 3 values:
0 Beginning of file
1 Current position
2 End of file

45
fseek()…
 The offset may be positive, meaning move forwards, or
negative, meaning move backwards.
 Examples:
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.) 46
fseek()…
 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.

47
/* A program that uses the functions ftell() and
fseek() */
#include <stdio.h> printf("\nCannot create file.");
void main() exit();
{ }
FILE *fp; n=0L;
char c; while(feof(fp)==0)
long n; {
clrscr(); fseek(fp,n,0); //Position to (n+1)th character
fp=fopen("RANDOM","w"); printf("Position of %c is %ld\n",fgetc(fp),ftell(fp));
if(fp==NULL) n=n+5L;
{ }
printf("\nCannot create file."); putchar('\n');
exit();
} fseek(fp,-1L,2); /*Position to the last character*/
while((c=getchar())!=EOF) do
fputc(c,fp); {
printf("\nNo. of characters entered=%ld",ftell(fp)); putchar(fgetc(fp));
}while(!fseek(fp,-2L,1));
fclose(fp); fclose(fp);
fp=fopen("RANDOM","r"); getch();
if(fp==NULL) }
{

48
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.

49
Explanation…
 The function feof(fp) gives nonzero value only when
all of the data from the specified file has been read. At
25th position feof(fp) gives 0 so that the condition
becomes true and the body gets executed.
 The file pointer crosses the end-of-file mark when the

parameter n of fseek(fp,n,0) becomes 30 so that after


printing the content of position 30, the loop is
terminated. (There is nothing in position 30.)
 For reading the file from the end, we use the

statement: fseek(fp,-1,2); so as to position the file


pointer to the last character.

50
Explanation…
 For reading the file from the end, we use the
statement: fseek(fp,-1,2); so as to position the file
pointer to the last character.
 Since every read causes the position to move forward

by one position, we have to move it back by two


positions to read the next character.
 This is done by the function fseek(fp, -2L, 1); in the

while statement.
 This statement also tests whether the file pointer has

crossed the file boundary or not………..the loop is


terminated as soon as the file boundary is crossed.

51
Problem
 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

52
#define SIZE 13 struct book bb[SIZE];
#include <stdio.h> clrscr();
void main() for(i=0;i<SIZE;i++)
{ {
struct book printf("\nEnter record of book
{ %d",i+1);
char title[40]; printf("\nEnter title:\t");
char author[20]; scanf("%s",b[i].title);
int pages; fflush(stdin);
float price; printf("\nEnter author:\t");
}; scanf("%s",b[i].author);
struct book b[SIZE]; printf("\nEnter no. of pages:\t");
int i; scanf("%d",&b[i].pages);
float temp; printf("\nEnter price:\t");
struct book *bp; scanf("%f",&temp);
FILE *fp; b[i].price=temp;
}

53
bp=b; //bp=&b[0];
for(i=0;i<SIZE;i++) rewind(fp);
{ fseek(fp,sizeof(b)*2,0);
printf("\nRecord of Book%d",i+1); i=2;
printf("\nTitle:%s\tAuthor:%s", printf("\nReading from file:");
(bp+i)->title,(bp+i)->author); while(fread(&bb,sizeof(bb),1,fp)==1)
printf("\nNo. of pages:%d\tPrice: {
%.2f\n",(bp+i)->pages,(bp+i)- while(i<SIZE-2)
>price); {
} printf("\nTitle:%s\tAuthor:%s",
bb[i].title, bb[i].author);
fp=fopen("booklist.dat","w+b"); printf("\nNo. of pages:%d\tPrice:
if(fp==NULL) %f\n", bb[i].pages, bb[i].price);
{ i++;
puts("Cannot create file"); }
exit(); }
} fclose(fp);
for(i=0;i<SIZE;i++) getch();
fwrite(&b,sizeof(b),1,fp); }

54
PROBLEM
 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.

55
question
 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.

56
#include <stdio.h> printf("\nDo you want to information for
void main() another employee(y for yes):");
{ scanf("%c", &ch);
struct employee }while(ch=='y');
{ rewind(fp);
char empname[20]; printf(“\n\tEnter employee to be searched:\t");
int age; fflush(stdin);
float salary; gets(name);
}; while(fread(&e,sizeof(e),1,fp)==1)
struct employee e; {
FILE *fp; if(strcmp(name, e.empname)==0)
char name[20]; {
char ch='y'; search=1;
int search=0; printf("\nName:%s", e.empname);
fp=fopen("C:\\employee.txt","w+b"); printf("\nAge:%d", e.age);
clrscr(); printf("\nSalary:%.2f", e.salary);
do }
{ }
printf("\nEnter name, age and salary of if(search==0)
employee:"); printf("\nThere is no employee with name
scanf("%s %d %f", e.empname, &e.age, %s", name);
&e.salary); fclose(fp);
fwrite(&e,sizeof(e),1,fp); getch();
fflush(stdin); }

57
PROBLEM
 Write a program to open a file employee.txt created
in above program and edit/modify the details of a
particular employee.

58
#include <stdio.h> while(fread(&e,sizeof(e),1,fp)==1)
void main() {
{ if(strcmp(name, e.empname)==0)
struct employee {
{ search=1;
char empname[20]; printf("\n Old record is:");
int age; printf("\n Name:%s",e.empname);
float salary; printf("\n Age:%d",e.age);
}; printf("\n Salary:%.2f",e.salary);
struct employee e; printf("\n Enter new record(name,age and
FILE *fp; salary):");
char name[20]; scanf("%s %d %f", e.empname, &e.age,
&e.salary);
int search=0;
fseek(fp,sizeof(e)*record_count,0);
int record_count=0;
if(fwrite(&e,sizeof(e),1,fp)==1)
fp=fopen("C:\\employee.txt","rb+");
printf("\nRecord modified!!!");
clrscr();
}
if(fp==NULL)
record_count++;
{
}
printf("Cannot open file");
if(search==0)
exit();
printf("\n There is no employee with name %s",
}
name);
printf("\tEnter employee name to be modified:\t");
fclose(fp);
gets(name);
getch();
}

59
PROBLEM
 Write an interactive C program that will maintain
roll, name, address and marks of students in a file
with following menu:
◦ Add new record
◦ Edit/Modify record
◦ Delete record
◦ Display all records
◦ Display records in alphabetical order of name
◦ Display information of given roll
◦ Display information of given name
◦ Display information of all students whose marks >= 80
◦ Display information of all students whose address is
“Kathmandu”

60
Strategies
 Addition of new records should take place at the end of
existing records in the file, i.e. in the same way new
records are added in a register manually.
 While modifying records, first we must ask the user

which record he intends to modify. Instead of asking


the record number to be modified, it would be more
meaningful to ask for the name of the student whose
record is to be modified. On modifying the record, the
existing record gets overwritten by the new record.

61
Strategies…
 In deleting records, except for the record to be deleted,
rest of the records must first be written to a temporary
file, then the original file must be deleted, and the
temporary file must be renamed back to original.
 Displaying all records means displaying the existing

records on the screen. Naturally, records should be


displayed from first record to last record.

62
#include <stdio.h>
void add_record();
void edit_record();
void delete_record();
void display_all_records();
void display_alphabetical_order();
void display_info_of_roll();
void display_info_of_name();
void display_marks_80();
void display_address_ktm();

struct student
{
int roll;
char name[20];
char address[20];
float marks;
};

63
void main()
{
char ch='y',option;
clrscr();

while(ch=='y')
{
printf("\n What do you want to do:");
printf("\n a--Add new record");
printf("\n b--Edit/Modify record");
printf("\n c--Delete record");
printf("\n d--Display all records");
printf("\n e--Display records in alphabetical order of name");
printf("\n f--Display information of given roll number");
printf("\n g--Display information of given name");
printf("\n h--Display information of all students whose marks>=80");
printf("\n i--Display information of all students whose address is KTM");

printf("\n Enter your option:\t");


scanf(" %c", &option);

64
switch(option)
{
case 'a': case 'g':
add_record(); display_info_of_name();
break; break;
case 'b': case 'h':
edit_record(); display_marks_80();
break; break;
case 'c': case 'i':
delete_record(); display_address_ktm();
break; break;
case 'd': default:
display_all_records(); printf("\nInvalid Option!!!");
break; }
case 'e': printf("\nDo you want to
display_alphabetical_order(); continue(y/n)?:");
break; ch=getche();
case 'f': }
display_info_of_roll(); getch();
break; }

65
void add_record()
{
struct student s;
FILE *fp;
char another='y';
fp=fopen("C:\\studmgmt.dat","rb+");
fseek(fp,0,2);
if(fp==NULL)
{
fp=fopen("C:\\studmgmt.dat","wb");
if(fp==NULL)
{
printf("\nUnable to create file.");
return;
}
}
while(another=='y')
{
printf("\nEnter roll, name, address and marks:\t");
scanf("%d %s %s %f",&s.roll,s.name,s.address,&s.marks);
fwrite(&s,sizeof(s),1,fp);
fflush(stdin);
printf("\nAdd another record(y/n)?:");
another=getche();
}
fclose(fp);
}

66
void edit_record() while(fread(&s,sizeof(s),1,fp)==1)
{ {
struct student s; if(strcmp(s.name,st_name)==0)
FILE *fp; {
char st_name[20]; printf("\n Enter new roll,name,address
int record=0; &marks:\t");
char another='y'; scanf("%d %s %s
fp=fopen("C:\\studmgmt.dat","rb+"); %f",&s.roll,s.name,s.address,&s.mark
if(fp==NULL) s);
{ fseek(fp,sizeof(s)*record,0);
printf("\nCannot open file."); fwrite(&s,sizeof(s),1,fp);
return; fflush(stdin);
} }
while(another=='y') record++;
{ }
printf("\n Enter name of student to printf("\n Modify another
modify:\t"); record(y/n)?:");
scanf("%s", st_name); another=getche();
}
fclose(fp);
}

67
void delete_record() {
{ if(strcmp(s.name,st_name)!=0)
struct student s;
FILE *fp; fwrite(&s,sizeof(s),1,fpp);
FILE *fpp; }
char st_name[20]; fclose(fp);
char another='y'; fclose(fpp);
fp=fopen("C:\\studmgmt.dat","rb+"); remove("C:\\studmgmt.dat");
if(fp==NULL) rename("C:\\temp.dat","C:\\
{ studmgmt.dat");
printf("\nCannot open file"); fp=fopen("C:\\
return; studmgmt.dat","rb+");
}
while(another=='y') printf("\nDelete another
record(y/n)?:");
{
fflush(stdin);
printf("\nEnter name of student to
delete:"); another=getche();
scanf("%s",st_name); }
fpp=fopen("C:\\temp.dat","wb"); fclose(fp);
while(fread(&s,sizeof(s),1,fp)==1) }

68
void display_all_records()
{
struct student s;
FILE *fp;
fp=fopen("C:\\studmgmt.dat","rb");
printf("\n Roll\t Name\t\t Address\t\t Marks");
while(fread(&s,sizeof(s),1,fp)==1)
printf("\n%d\t%s\t%s\t\t%f", s.roll, s.name,
s.address, s.marks);
fclose(fp);
}

69
void display_alphabetical_order()
{ for(i=0;i<no_of_records-1;i++)
struct student s,*st,temp; {
FILE *fp; for(j=i+1;j<no_of_records;j++)
int no_of_records=0; {
int i,j; if(strcmp((st+i)->name,(st+j)->name)>0)
fp=fopen("C:\\studmgmt.dat","rb"); {
while(fread(&s,sizeof(s),1,fp)==1) temp=*(st+i);
no_of_records++; *(st+i)=*(st+j);
st=(struct student *(st+j)=temp;
*)malloc(no_of_records*sizeof(struct }
student)); }
}
rewind(fp);
printf("\n Records in alphabetical order:");
for(i=0;i<no_of_records;i++) for(i=0;i<no_of_records;i++)
{ printf("\n%d\t%s\t%s\t%f",(st+i)->roll,
fread(&s,sizeof(s),1,fp); (st+i)->name,(st+i)->address,(st+i)-
*(st+i)=s; >marks);
}
fclose(fp);
}

70
void display_info_of_roll() search=1;
{ printf("\n Student with
struct student s; roll no. %d is:",r);
int r; printf("\nName\
FILE *fp; tAddress\tMarks");
int search=0; printf("\n%s\t%s\t
fp=fopen("C:\\ %f",s.name,s.address,s.mark
studmgmt.dat","rb"); s);
printf("\n Enter roll no. you break;
want to search:\t"); }
scanf("%d",&r); }
while(fread(&s,sizeof(s),1,fp)== if(search==0)
1) printf("\n There is no student
{ with roll no. %d",r);
if(s.roll==r) fclose(fp);
{ }

71
void display_info_of_name() printf("\nThe record of
{ student with name %s
struct student s; is:",st_name);
FILE *fp; printf("\nRoll\tAddress\
char st_name[20]; tMarks");
int search=0; printf("\n%d %s
%f",s.roll,s.address,s.marks);
fp=fopen("C:\\
studmgmt.dat","rb"); break;
printf("\nEnter student name to }
be searched:\t"); }
scanf("%s",st_name);
while(fread(&s,sizeof(s),1,fp)==1 if(search==0)
) printf("\nThere is no student
{ with the name %s.",st_name);
if(strcmp(s.name,st_name)==0) fclose(fp);
{ }
search=1;
72
void display_marks_80()
{
struct student s;
FILE *fp;
int search=0;
fp=fopen("C:\\studmgmt.dat","r");
printf("\n Record of students with marks>=80");
while(fread(&s,sizeof(s),1,fp)==1)
{
if(s.marks>=80)
{
search=1;
printf("\nRoll No.=%d",s.roll);
printf(" Name=%s",s.name);
printf(" Address=%s",s.address);
printf(" Marks=%f",s.marks);
}
}

if(search==0)
printf("\n There is no student with marks>=80.");
fclose(fp);
}

73
void display_address_ktm()
{
struct student s;
FILE *fp;
int search=0;
fp=fopen("C:\\studmgmt.dat","r");
printf("\n Record of students with address \"Kathmandu\"");
while(fread(&s,sizeof(s),1,fp)==1)
{
if(strcmp(s.address,"Kathmandu")==0)
{
search=1;
printf("\nRoll=%d",s.roll);
printf(" Name=%s",s.name);
printf(" Marks=%f",s.marks);
}
}
if(search==0)
printf("\n There is no student from \"Kathmandu\"");
fclose(fp);
}

74
Model Question
 Arrange the master file in descending order of average
marks and create a new file.

75
#include <stdio.h>
void main() for(i=0;i<count-1;i++)
{ {
FILE *fp,*fpp; for(j=i+1;j<count;j++)
float avg; {
float *p; if(*(p+i)<*(p+j))
int count=0; {
int i,j; temp=*(p+i);
float temp; *(p+i)=*(p+j);
fp=fopen("C:\\master.txt","r"); *(p+j)=temp;
fpp=fopen("C:\\descend.txt","w"); }
}
clrscr(); }
while(fscanf(fp,"%f",&avg)!=EOF)
count=count+1; for(i=0;i<count;i++)
fprintf(fpp,"%f\t",*(p+i));
p=(float *)malloc(count*sizeof(float));
fclose(fp);
rewind(fp); fclose(fpp);
getch();
for(i=0;i<count;i++) }
fscanf(fp,"%f",(p+i));

76
Question
 Suppose a store has a number of items in their
inventory and that each item is supplied by at most two
suppliers. Create inventory and supplier files. Find the
address of all suppliers who supply more than 10
different items. Discuss any changes in the data
structure you suggest to simplify solving this problem.

77
#include <stdio.h> scanf("%d",&m);
void main() s=(struct store*)malloc(m*sizeof(struct store));
{ for(i=0;i<m;i++)
struct supplier {
{ printf("\nEnter info about item%d",i+1);
char name[10]; printf("\nEnter item name:\t");
char addr[10]; scanf("%s",(s+i)->item);
}; fflush(stdin);
struct store printf("\nEnter first supplier's name:\t");
{ scanf("%s",(s+i)->sup1);
char item[10]; fflush(stdin);
char sup1[10]; printf("Is there a second supplier(y/n):\t");
char sup2[10]; scanf("%c",&yn);
}; fflush(stdin);
struct store *s; if(yn=='y')
struct supplier *sp; {
int m,n; printf("\nEnter second supplier's name:\t");
int p,q; scanf("%s",(s+i)->sup2);
int i,j; fprintf(fp,"%s %s %s\n",(s+i)->item,(s+i)-
char yn; >sup1,(s+i)->sup2);
char x[10],y[10],z[10]; }
int count; else
FILE *fp,*fpp; {
clrscr(); fprintf(fp,"%s %s NULL\n",(s+i)->item,(s+i)-
fp=fopen("C:\\inventor.txt","w"); >sup1,(s+i)->sup2);
fpp=fopen("C:\\supplier.txt","w"); }
printf("\nHow many items:\t"); }

78
printf("\nHow many suppliers:\t");
scanf("%d",&n);
sp=(struct supplier*)malloc(n*sizeof(struct fp=fopen("C:\\inventor.txt","r");
supplier)); count=0;
for(i=0;i<n;i++) fpp=fopen("C:\\supplier.txt","r");
{
printf("\nEnter info about supplier%d",i+1); p=0;
printf("\nEnter supplier's name:\t"); while(fscanf(fp,"%s %s %s",x,y,z)!=EOF)
scanf("%s",(sp+i)->name); p++;
fflush(stdin);
printf("\nEnter supplier's address:\t"); q=0;
scanf("%s",(sp+i)->addr); while(fscanf(fpp,"%s %s",x,y)!=EOF)
fflush(stdin); q++;
fprintf(fpp,"%s %s\n",(sp+i)->name,(sp+i)-
>addr); s=(struct store *)malloc(p*sizeof(struct store));
} sp=(struct supplier *)malloc(q*sizeof(struct
free(s); supplier));
free(sp);
fclose(fp); rewind(fp);
fclose(fpp); rewind(fpp);

79
for(i=0;i<p;i++) >sup1)==0) || (strcmp((sp+i)->name,
{ (s+j)->sup2)==0))
fscanf(fp,"%s %s %s",(s+i)->item, count=count+1;
(s+i)->sup1,(s+i)->sup2); if(count>10)
printf("\n%s %s %s\n",(s+i)->item, {
(s+i)->sup1,(s+i)->sup2); printf("\nSupplier's address
} supplying>10 items=%s\n",(sp+i)-
for(i=0;i<q;i++) >addr);
{ break;
fscanf(fpp,"%s %s",(sp+i)->name, }
(sp+i)->addr); }
printf("\n%s %s\n",(sp+i)->name, count=0;
(sp+i)->addr); }
}
fclose(fp);
for(i=0;i<q;i++) fclose(fpp);
{ getch();
for(j=0;j<p;j++) }
{
if((strcmp((sp+i)->name,(s+j)-
80
Suggestion
 By using the structure of store as in the program, we are
compelled to provide second supplier’s name even if
there is no second supplier (in which case we are
providing NULL).
 The structure looks like this:

Item Sup1 Name


Sup2 Addr
A0 ABC ABC
XYZ MNR
A1 ABC XYZ
NULL KTM
A2 XYZ
NULL

INVENTORY.TXT SUPPLIER.TXT
81
Suggestion…
 Because of this structure, for finding the address of
suppliers that supply more than 10 items, we have to take
one supplier’s name from supplier.txt file and do
comparison with supplier1 and supplier2 in inventory.txt
file.
 Let there are 15 items in the inventory. Let 10 items are
supplied by two suppliers and 5 items are supplied by
only one supplier (the second supplier is NULL).
 Since we cannot assume, for which item the second
supplier is NULL, we have to perform comparison with
both of the two suppliers, thus in this case there are 30
comparisons to be made.
82
Suggestion…
 Changing the structure of store to providing only the
name of the item and the name of a supplier one at a
time, we can provide the whole information without
having NULL values.
 Now the structure looks like:

Item Name
Sup Addr
A0 ABC
ABC MNR
A0 XYZ
XYZ KTM
A1
ABC
A2
INVENTORY.TXT
XYZ SUPPLIER.TXT
83
Suggestion…
 Because of this structure, for finding the address of
suppliers that supply more than 10 items, we have to
take one supplier’s name from supplier.txt file and do
comparison with one supplier at a time in inventory.txt
file.
 Assume the same case. Let there are 15 items in the

inventory. Let 10 items are supplied by two suppliers


and 5 items are supplied by only one supplier. So
overall, there are 25 records. So that, there are only 25
comparisons to be made--------this is BETTER!!!
 This suggestion is illustrated by the following program:

84
#include <stdio.h>
void main() for(i=0;i<m;i++)
{ {
struct supplier printf("\nEnter info about item%d",i+1);
{ printf("\nEnter item name:\t");
char name[10]; scanf("%s",(s+i)->item);
char addr[10]; fflush(stdin);
}; printf("\nEnter supplier's name:\t");
struct store scanf("%s",(s+i)->sup_name);
{ fflush(stdin);
char item[10]; fprintf(fp,"%s %s\n",(s+i)->item,(s+i)->sup_name);
char sup_name[10]; }
};
struct store *s; printf("\nHow many suppliers info:\t");
struct supplier *sp; scanf("%d",&n);
int m,n; sp=(struct supplier*)malloc(n*sizeof(struct supplier));
int p,q; for(i=0;i<n;i++)
int i,j; {
char x[10],y[10]; printf("\nEnter info about supplier%d",i+1);
int count; printf("\nEnter supplier's name:\t");
FILE *fp,*fpp; scanf("%s",(sp+i)->name);
fp=fopen("C:\\inventor.txt","w"); fflush(stdin);
fpp=fopen("C:\\supplier.txt","w"); printf("\nEnter supplier's address:\t");
clrscr(); scanf("%s",(sp+i)->addr);
fflush(stdin);
printf("\nHow many record of items:\t"); fprintf(fpp,"%s %s\n",(sp+i)->name,(sp+i)->addr);
scanf("%d",&m); }
s=(struct store*)malloc(m*sizeof(struct store)); free(s);
free(sp);
fclose(fp); 85
for(i=0;i<q;i++)
fp=fopen("C:\\inventor.txt","r"); fscanf(fpp,"%s %s",(sp+i)->name,(sp+i)->addr);
count=0;
fpp=fopen("C:\\supplier.txt","r"); for(i=0;i<q;i++)
{
p=0; for(j=0;j<p;j++)
while(fscanf(fp,"%s %s",x,y)!=EOF) {
p++; if(strcmp((sp+i)->name,(s+j)->sup_name)==0)
count=count+1;
q=0; if(count>10)
while(fscanf(fpp,"%s %s",x,y)!=EOF) {
q++; printf("Supplier's address supplying>10 items=
%s\n",(sp+i)->addr);
s=(struct store *)malloc(p*sizeof(struct store)); break;
sp=(struct supplier *)malloc(q*sizeof(struct }
supplier)); }
count=0;
rewind(fp); }
rewind(fpp);
fclose(fp);
for(i=0;i<p;i++) fclose(fpp);
fscanf(fp,"%s %s",(s+i)->item,(s+i)->sup_name); getch();
}

86
Question
 Assume that at the end of the year, a set of student join
the class and another set leaves. Using the roll number
and an appropriate code to add or delete a student,
update the master file. The updated file should be in
ascending order of the roll number.

87
#include <stdio.h> {
void main() printf("\n Enter info. about student%d",i+1);
{ printf("\n Enter batch:\t");
struct student scanf("%s",(s+i)->batch);
{ printf("\n Enter roll:\t");
char batch[10]; scanf("%d",&((s+i)->roll));
int roll; printf("\n Enter name:\t");
char name[20]; scanf("%s",(s+i)->name);
}; fflush(stdin);
struct student *s, temp; }
char b[10]; for(i=0;i<m-1;i++)
int r; {
char n[20]; for(j=i+1;j<m;j++)
int i, m, j; {
FILE *fp, *fpp; if((s+i)->roll>(s+j)->roll)
clrscr(); {
fp=fopen("C:\\master.txt","r"); temp=*(s+i);
fpp=fopen("C:\\backup67.txt","w"); *(s+i)=*(s+j);
while(fscanf(fp,"%s %d %s",b,&r,n)!=EOF) *(s+j)=temp;
fprintf(fpp,"%s %d %s\n",b,r,n); }
fclose(fpp); }
fclose(fp); }
fp=fopen("C:\\master.txt","w"); for(i=0;i<m;i++)
printf("\n How many new students?:"); fprintf(fp,"%s %d %s\n",(s+i)->batch,(s+i)->roll,
scanf("%d", &m); (s+i)->name);
s=(struct student*)malloc(m*sizeof(struct student)); fclose(fp);
for(i=0;i<m;i++) getch();
}

88
Question
 Given a text file, create another text file deleting all
the vowels (a, e, i, o, u).

89
#include <stdio.h> printf("Cannot create file");
void main() exit();
{ }
FILE *fp,*fpp;
char c; while((c=fgetc(fp))!=EOF)
fp=fopen("C:\\test.txt","r+"); {
clrscr(); if((c!='a')&&(c!='e')&&(c!
if(fp==NULL) ='i')&&(c!='o')&&(c!='u'))
{ fputc(c, fpp);
printf("Cannot open file");
exit(); }
}
fpp=fopen("C:\\hello.txt","w"); fclose(fp);
if(fpp==NULL) fclose(fpp);
{ getch();
}

90

You might also like