0% found this document useful (0 votes)
2 views

c Programing 2

The document outlines the rules for passing arguments by pointers in C, emphasizing the need for matching types and the use of indirection operators. It also discusses function nesting and recursion, providing examples of how functions can call one another and how recursion can be used to calculate factorials. Additionally, it covers variable scope, visibility, and lifetime, along with the definition and use of structures and unions for organizing complex data.

Uploaded by

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

c Programing 2

The document outlines the rules for passing arguments by pointers in C, emphasizing the need for matching types and the use of indirection operators. It also discusses function nesting and recursion, providing examples of how functions can call one another and how recursion can be used to calculate factorials. Additionally, it covers variable scope, visibility, and lifetime, along with the definition and use of structures and unions for organizing complex data.

Uploaded by

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

Rules for Pass by Pointers

1. The types of the actual and formal arguments must be same.


2. The actual arguments (in the function call) must be the addresses of variables
that are local to the calling function.

3. The formal arguments in the function header must be prefixed by the indirec
tion operatior.

.
4. In the prototype, the arguments must be prefixed by the symbol *.
5. To access the value of an actual argument in the called function, we must use
the corresponding formal argument prefixed with the indirection operator

9.15 NESTING OF FUNCTIONS


buctoneunck'on Car (at anothe dtroo wh
bhortog
C permits (nesting of functions freely. main can call functionl, which calls function2,
which callsfunction3, and so on. There is in principle no limit as to how deeply
functions can be nested.
Consider the following program:
User-Defined Functions H207

float ratio (int x, int y, int z);


int difference (int x, int y);
main( )

int a, b, C;
Scanf("d %d %d", &a, &b, c);
printf("%f \n", ratio(a,b,c));

float ratio(int x, int y, int z)


{
if(difference(y, z))
return(x/(y-z));
else
return (0.0);

nint difference(int p, int q)

if(p != q)
return (1);
else
return (0);
in ANSI C
288 Programming

9.6 RECURSION
process of chaining occurs. Recur.
a
When called funetion in turn calls another function A very simple
a
calls itself example
sion is a special case af this process, where a function
recursion is presented below:

Shote main( )
of recursion\n")
an example
printf("This is
main( );

like this:
output something
When executed, this program will produce an
This is an example of recursion
This is an example of recursion
This is an example of recursion
This is an ex
execution will continue indefinitely.
Execution terminated abruptly:otherwise the
is
is the evaluation of factorials
of a given number. The
Another useful example of recursion mulipications as shown below:
factorial of a number
n is expressed as a series of repetitive
factorial of n n(n-1)\(n-2)....1. =
For example,
factorial of 4 = 4X3×2x1= 24

A function to evaluate factorial of n is as follows:

factorial (int n)

int fact;
if (n==1)wollkt a
return(1);
else
fact = n*factorial (n-1):;
return(fact);

n=3. Since the value of n is not 1, the state


Let us see how the recursion works, Assume
ment
ars fact =n * factorial (n-1);
will be executed with n =3. That is,

fact = 3 * factorial (2);


be evaluated. The expression on the right-hand side includes a factorial
call to with
will

n=2. This call will return the following value:


femt 2*factorial(1)
is called withn=1,This time, the function returns 1. The sequence 0
Once again, factorial
as follows:
operations can be summarized
User-Defined
Functions
In pass by pointers |295
(alsoknown
cather than as pass
variables the by
address), the
the called
copies of
values are sent memory addressesof the
case, function directly
tothe called function. In this
works on the datainthe
changed values are available in the function and the
calling
calling
Pass by pointers
functionforits
method is
uše.
is often used when
This method also used strings.
when we manipulating artays and
function. require
called multiple values to be returned by the

9.19
THE SCOPE, VISIBILITY AND
LIFETIME OF VARIABLES 1om Sm
iahlesin C difter in behaviour from
Sho<09 lone
those in most other languages. For example, in
variable a
BASIC program, a retains its value
in C. It all depends on the 'storage'class a
throughout the programn. It is not always the
variable may assume.
Io C not only do all variables have a data type,thev also
have a storage class. The follow
variable storage classes are most relevant
to functions:

1. Automatic variables.
2. External variables.

3. Static variables.

4. Register variables.

We shall briefly discuss the scope, visibility and longevity of each of the above class of
variables. The scope of variable determines over what region of the program a variable is

actually available for use ('active'). Longevity refers to the period during which a variable
retains a given value during execution of a program ('alive').So longevity has a direet effect
on the utility of a given variable. The visibility refers
to the accessibility of a variable from

the memory.

The variablesmay also be broadly categorized, depending


on the place of their declara

tion, as internal (local) or external (global). Internalvariables are those which are declared
outside of any function.
within aparticular function, while external variables are declared
lt is very important to understand
the concept of storage classes and their utility in order

to developefficient multifunction programs.

Automatic Variables2m
which they areto be utilized. They are
inside a function in
Automatic variables are declared
called and destroyed automnatically
when the function is exited.
reated when the function is
private (or local) to the Fune.
Automatic variables are therefore
e the name automatie. variables are also re
thev are declared. Because of this property, autonmatie
In which
ferred to
as local internal
or variables.
class specification is, by default, an
A function without storage
variable declared inside a
of the variable number in the example
automatic the storage class
variable. For instance,
Delow is
automatic.
10
Stru tures and
|Unions

0.1 INTRODUCTION

We have seen that arrays can be used to


such as int or represent a group of data items that belong to the
Same type, float. However, wecannot use an arrayif we
Stion of data items of
want to represent a
different types using a single name,
onstructed data type known asstructures, a Fortunately(C supports
structure
mechanism
is a convenient tool for handling a
for
packing data of difrerenttypes
group logically related data items For
of

ample, it can be used to represent a set of attributes,


such as student_name, roll_nunber
and marks. The concept of a structure is
analogous to that of a 'record'in many
languages. More examples of such other
structures are:
time seconds, minutes,hours
date day, month, year
book author, title, price, year
city name, country, population
address name, door-number, street, city
inventory item, stock, value
customer name, telephone,city, category
Structureshelp to organize complex data in a more
meaningful way. It is a powerfu
conceptthatwe may often need to use in our program design.This
chapter is devoted to th
study of structures and their applications in program development. Another
related concep
Knownas unions is also discussed.

02DEFINING A STRUCTURE
Unlike
declare
arrays(structures must be defined first for their format that may be used later
structure variables Let us use an example to illustrate the process of
structur
definition and the creation of structure variables. Consider a book database
consisting
10
structures and
Unions
INTRODUCTION
10.1

seen that
arrays can be
We bave
such as int or float. used to represent a group data itemsthat belong to the
of

same type, However,we cannot use


data items of
of an array if we want to represent a)
different types
anllection using a single
data type knoWn as name. Fortunately(C supports a
Cnstructed structures, a
is a convenient tool for mechanism for packing data of dinerent tpes
A structure handling
can be used to represent a set of group of logieally related data iens For
Sample, it
a

The concept of a structure is attributes, such as student_name, roll number


And marks. analogous to that of a 'record'in many other
More examples of such structures
languages. are:
time seconds, minutes, hours
date day, month, year
book author, title, price, year
city name, country, population
address name, door-number, street, city
inventory item, stock, value
customer name, telephone, city, category
Structures help to organize complex data in a more meaningful way. It is a powerful
oncept that we may often need to use in our program design. This chapter is devoted to the
study structures and their applications in program development. Another related concept
of

known as unions is also discussed.

10.2 DEFINING A STRUCTURE


Unlike arraysstructures must be defined first for their format that may be used later to
declare structure variables, Let us use an example the process of structure
to illustrate
deinition and the creation of strueture variables, Consider a book database consisting of
10.3
DECLARINGSTRUCTURE
VARIABLES
defining a structure format we can declare
After
variables of that type.A structure variable
eclaration is similar to the declaration of
variables of any other data types. It includes the
following elements:
(1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas
4. terminating semicolon.
A

For example, the statement


7struct book bank, bookl, book2, book3;) G

declares book1, book2, and book3 as variables of type struct book_bank.


Each one of these variables has four members as specified by the template.The complete
declaration might look like this:
struct book bank

char title[20];
char author [15] ;
int pages;
float price;

(struct book bank bookl, book2, book3;

themselves are not variables. They do not


a structure
Remember that the members of structure variables such as booki.
with the
until they are associated space for the
vecupy any memory it reserves memory
across a declaration statement,
When thecompiler comes structure definition
and variables
to combine both the
Saructure variables. It is also allowed
declaration in one statement.
Structures and Unions 321

ACCESSING STRUCTURE MEMBERS y

and assign values to the


access
We can members of a structure in
a number of ways. A

earlier, the members


mentioned themselves are not variables.They should be linked to the
variables in order to make them
structure meaningful members. For example, the word
has no meaning whereas the
title, phrase'title of book3 has a meaningThe link between a
and a variable is
member established using the member operator which is also known as
dot operator' or'period operator For example,

6sthe variable
bookl.price )
representing the price of bookl and can be treated like any other ordinary
eariable. Here is how we would assign values to the members
of bookl:
strcpy (bookl.title, "BASIC"):
strcpy (bookl.author, "Bal agurus amy"):
bookl.pages = 250;
bookl.price = 120.50;
We can also use scanf to give the values through the keyboard.

scanf ("%s\n",book1.title);
scanf("%d\n",
&bookl.pages):)
are valid input statements.
Structuresand Unions H327

ana ARRAYS OF STRUCTURES X Sm


For example, in
to describe theformat of a number related variables.
We use structures
of
to describe
the marks obtained by a class of students,(we mayuse a template
analyzing in various subiects then declare all the students as
nd
tudent name and marks obtained each element
of
structures,
In such cases, we may declare an array of
structure variables..
a structure variable. For example:
the array representing
struct class student [100] : is defined to be
that consists of 100 elementsEach element
Cdefines an array called student, declaration:
class. Consider the following
of the type struct
marks
struct

int subjectl;E0S
int subject2;
int subject3;

main()

marks student [3]


struct (57,36,71}}:|
(75,53,69}, 1], and
({45,68,81), student[
elements student[0],
student as an array of three
the as follows:
This declares their members
and initializes = 45:;
student[2] student [0].subject1 = 68;
student [0].subject2

= 71; Sinc
student [2].subject3 any other array,
been with elemen
would have individual
just as it to access
array is declared methods element of stude
the array-accessing each
Note that use theusual
is an array, we
to access members. Remember,
student amulti-dimensior
then the member operator three members. in the same way as
and variable
with
memory
is a structure inside the
array is stored in Fig. 10.3.
structures looks as shown
An array of actually calculate
The array student program to
a

them as a pat of
above, write
array.
Structures and
Unions
ARRAYS OF 327
T0.8
We use
structures
to
STRUCTURES
describe the
XSn
zing the marks obtained byformat
a
of a
number
naly of
name and marks obtained class of related I variables, For example, in
student
In such in various Subswe miusea template to descrihbe
variables
structure cases, we may al the stodents as
Tnd then declare
rejpresenting ga declare
the array structure an array ot structures, each element of

:
variable. For
example:
e47struct class
array r called student [100]
defines an student,
struet that consists of 100
ofthe type class. Consider
the elementasEnch element is defined to be
following
declaration:
struct marks

int
subjectl;
int subject2;
int subject3:

main()

struct marks student [3)


{(45,68,81), (75,53,69). (57,36,71}1:
This the student as an array of three
declares
elements student[0], student[1l, and
student[2] and initializes their members as
follows:

student [0].subject1 = 45;


student [o].subject2 = 68;

student [2].subject3 = 71;


Note that the array is declared just as
would have been with any other array. Since
it

studentisan array, we use the usual array-accessing methodsto access individual elements
andthen the member operator to access members. Remember, each element of student
a
array is structure variable with three members.
An array ofstructures is stored inside the memory in the same way as amulti-dimensional
array. The array student actually looks as shown in Fig. 10.3.
Fig. 10.4 Arrays of
structures: Illustration structure variables
of subscripted

10.9
ARRAYs WITHIN STRUCTURES X"Sm
the use
of arrays as structure members. We have already used arrays
of charac-
C permits arrays
a structure. Similarly{ we
inside can use single-dimensional or multi-dimensional
ters
int or float. For example, the following structure declaration is valíid:
of type
struct marks

int number;
float subject [3]:
} student[2];

contains three elements, subject[0), subject[1] and


Here, the member subject
the
can be accessed using appropriate subscripts. For example,
subject[2].These elements
name
student [1].subject [2]:
by the second student.
would refer to the marks obtained in the third subject

of Exanmple 10.3 using an array member to repr


10.4| Rewrite the program
Example
subjects.
sent the three
of array name
may notice that the use
is shown in Fig. 10.5. You
The modified program
in code.
subjects has simplified
Structures and Unions
331
STRUCTURES WITHIN STRUCTURES
10.10

within a
structure means nesting
Structures of
us
consider thefollowing structures. Nesting of structures is permit-
C. Let
ted in structure definedto store
information about the salary
of employees.
struct sal ary

char name;
char department;
int basic pay;
int dearness àllowance:
int house rent allowance;
int city allowance;

employee;

This structure defines name, department, basic pay and three kinds of allowances. We can
as
gTOup all the items related to allowance together and declare them under a substructure
shown below:
struct salary

char name;
char department;
struct

int dearness;
int house rent;
int city;

all owance;

employee;
which itself is a structure
contains a member named allowance, dearness,
The salary structure structure namely
The members contained in the inner
with three members.
can be referred to as:
house_rent, and city
employee.allowance.dearness
rent
employee.allowance.house
employee.allowance.city all the con
accessed by chaining
a nested structure can be
An inner-most member mnember using dot op
in
(from outer-most to inner-most) with the
cernedstructure variables
erator.The following are invalid: is missing)
(actual member
employee.allowance is missing)
(inner structure variable
employee.house rent is
following form of declaration
can have more than one variable. The
An inner structure
legal:
Structures and Unions |333

STRUCTURES AND FUNcTIONS s e 2r


We know thatthe main philosophy of C language is the use of funetions, And therefore, it is
that C supports the passing of structure values as
arguments to functions. There
are
natural s
methods by which the values of a structurecan be transferred from one function to
three
another.
1. The first methodis to pass each member of the structure as nn aetual argument of the
function call.The actual arguments arethen treated independently ike ordinary vari
ables.This is the most elementary method and becomes unmanngeable and inetieient
when the structure size is large.
2. The second method involves passing of a
copy of the entire slructure to the called
function. Sincethe function is working on a copy of the structure, any change
in the original structure (in
structure members within the function are not reilected
to return the entire
the calling function).It is, therefore, necessary for the function
may not support this method
structure back to the calling function. All compilers

of
passing the entire structureas a parameter.
as an argu
3. The third approach employs a concept called pointers topass the structurecalled func
is passed to the
ment. In this case, the address location of the structure
the entire structure and work on it. This is
tion. The function can access
indirectly
more eficient as
are passed to function. This method
is
similar to the way arrays
compared to the second one. third approach using
in detail the second method, while the
In this section, we diséuss dealt in detail.
next chapter, where pointers are
pointers is discussed in the function is:
of a structure to the called
The general formnat of sending a copy

Synton
function name (structure_variable name);
formn:
The called function takes the following
(struct type st name)
data type function name

return (expression) :
The following points are important to note;
for its type, appropriate to the data type it is

The called function must be declared


of the entire structure, the
1.
is returning a copy
expected to return. For example. ifit

it must be declared as struct


with an appropriate tag name,
and the corresponding forma
2. "The structure variableused as the actual argument
of the same struet type.
argument in the called function must be
when the function is returning some dat
3. The return statement is necessary only
or structur
to the calling function Theexpression may be any simple variable
ble or an expression using simple variables.
varables adds
data ndnecr
ech
y
by ohtch
pott
Qnoe Vaable memoy b
holdthe addcm
Pio

atd 11
Pointers
vatable hen (eyam) s
knGon

11.1
INTRODUCTION
Apointer is a derived
data type in C
available in It is
C,(Pointers contain built
from one the fundamental data types
of
addresses are the locations memory
in the addresses as their yalue. Since these
memory
are stored,(pointers
can be used tocomputer memory where program instructions and
Pointers are access and
data
undoubtedly one manipulate data stored in the
has added power and the of
most distinct memory.)
lexibility to the and exciting features of C language. It
difficult to language, Although they
understand for a beginner, appear little confusing
are mastered. they are a powerful and
tool and handy
to use once
Pointers are used they
frequentlyin C, as they offer
They include: a number of benefits to
theprogrammerS.
1. Pointers are
more efficient in
2. Pointers can be used handling arrays and
to return multiple values data tables.
ments. from functionvia a
argu
function
3. Pointers permit references
to functions and
as arguments to other thereby facilitating passing of
functions. functions
4. The use pointer arrays to
of
character strings results in
memory. saving of data storagespace in
5. Pointers allowto support dynamic
C
memory management.
6. Pointers provide an eficient tool for manipulating
dynamic data structures such as
structures, linked lists,queues, stacks and
trees.
7. Pointers reduce length and complexity of
programs.
8. They increase the execution speed and thus
reduce theprogram execution time.
Of course, the real power of C lies in the proper use of
pointers.In this chapter, we will
examine the pointers in detail and illustrate how to use them
in program development.
Chapter 13 examines the use of pointers for creating and managing linked lists.

11.2 UNDERSTANDING POINTERS

The computer's memory is a sequential collection of storage cells as shown in Fig. 11.1. Each
cell, commonly known as a byte, has a number called address associated with it. Typicaly
11.3 ACCESSING THE ADDRESS OF A VARIABLE

The actual location of a variable in the memory is system dependent and therefore
address of a variable is not known to us immediately. How can we then determin
address of a variable? This can be done with the help of the operator &
available in
have already seen the use of this address operator in the seanf function.The opera
immediately preceding a variable returns the address of the variable associated with
example, the statement
p = &quantity;
the address 5000 (the location of quantity) to the variable p. The & op
(wouid assign
can be remembered as 'address of".
The fo
(The operator can be used only with a simple variable or an array element)
&
are illegal use of address operator:
1. &125 (pointing at constants).
2. int x[10];
&x (pointing at array names).
3. &(x+y) (pointing at expressions).
as
If x is an array, then expressions such
and &xi+3
(&
of Oth and (i+3)th elements of x.
the addresses
are valid and represent
along with
the address of a variable
it

Example 11.1|Write a program to print


and then
declares and initializes four variables
The program shown in Fig. 11.4, storage locations. Note that we have used %u
respective
these values with their
Memory addresses are unsigned integers.
printing address values.

Program
main()

char
int
Fig 11.4
Accessing the address of a
variabie
DECLARING POINTER
VARIABLES
In C.fevery variable must be
declared for its type.
that belong to a separate data addresses

P Since pointer variables contain


he
:
type, they must
declaration ofa pointer variable be declared as pointers before we use them.

t akes the following form:


dto pofo vaabie
data type
his tells the compiler three *pt_name; )Syntar
thingsaboutthe variable
The asterisk ()tells
1.
that the variable pt name pt_name.
pt_name needs a memory location.
2. is a pointer variable.
3. pt _name points toa
variable of typedata_type.
For example,

declaresthevariable p
int "p:)* integer pointer */oPTn
as a pointer variable that points to an integer
that the type int refers to the data type

float *x; |*float pointer */


data
of the variable being pointed to by
of the value of the pointerl Similarly, the statement p&x assianaa
X
e
type.Remember
p and not the type
and p
aolc
declaresx as a pointer to a floating-point
variable.
Thedeclarations cause the compiler to allocate memory locations for the pointervariables

+
p and x.Since the memory locations
have not been assignedany values, these
locationsmay
contain some unknown values in them and therefore
they point to unknown locations as
shown:
Ha 2ano mE rmc A
peun te uaie adcde
12
File
in Management C
12.1 INTRODUCTION
Until now we have been
using the
These are console oriented /O functions such ass scanf and printf to read and write data.
sereen) asthe target functions, which
place. This works always use the terminal (keyboard and
fine as long as
life problems involve large the data is small. However, many real-
volumes of data and in
onerations pose two major problems. such situations, the console oriented I/O

1. It becomes cumbersome and time


consuming to bandle large
terminals. volumes of data througn
2. The entire data is lost when either the nrogram is terminated or the computer
turned off. i8

It is therefore necessary to have a more flexible


approach
disks and read whenever where data can be stored on
necessary, without destroving the data. This te
concept of filesto store data.A file is a place on method employs the
a
the disk where group of related data i5
stored. Like most otherlanguages, C supports a number of
functions that have the ability to
-performn basic file operations, which include:

naming a file,
opening a file,
• reading data from a file,
writing data to a file, and
closing a file.

There are two distinct ways to perform file operations in C. The first one is known as the
low-level IO
and uses UNIX system calls. The second method is referred to as the high-level
IO operation and usesfunctions in C's standard I/O library. We
shall discuss in this chapter,
the important file handling functions that are available in the C library. They are listed in
Table 12.1.
390 Programming in ANSIC

Table 12.1 High Level l/O Functions

unction name nration


Creates a new file for use.
fopen)
Opens an existing ile for usc.

felose) Closes a file which has beenopencd for use.


getc) Reads a character from a file.

Writes a character to a file.


pute)
fprintf) *Writes a set of datavalues to a ile

fscant)
getw)
Rendsa set
*Readsan integer
of datavalues from a file.
from a file.
M sli
to a ile.
Writes an integer
putw)
to a desired point
in the file.
fseek() "Sets the position
the current position in the file (in terqs of bytes from the start
ftell() Gives
*
ofthe file.
*Sets the position to the beginning
Om rewind(0

compilers.You
There are many other functions, Not all of them are supported by all shoula

check your C library before using a particular I/O function.

12.2 DEFINING AND OPENING A FILE

.
If we want to store data in a file in the secondary memory, we must specify certain things

about the file, to the operating system. They include:


1.Filename ^
2.Data structure.
Sns -Pead
3. Purp0se.
opuaaa
Filename is a string of characters that make up a valid filename for the operating system.

It
may contain two parts, a primary name and an optionalperiod with the extension. Exam
ples:

Input.data
store
PROG.C
Student.c
Text.out
Data structureof a file is defined as FILE in the library of standard I/O function delini
tions. Therefore, all files should be declared as type FILE before they are used. FILE s a

defined data type


When weopen a file, we must specify what we want to do with the file. For example, we
may write data to the file or read the already existing data.
Following is the general format for declaring and opening a file:

FILE *fp;
tp fopen ("filename", "mode"):)

The first statement declares the variable fp as a "pointer to the data type FILE". AS
stated earlier, FILE isa structure that is defined in the I/O library. The second stalement
File Management in C 391
the fle named filename and assigns an fp. This
opens identifier to the FILE type pointer
which contains all the information as a commu-
pointer, about the file is subsequently used
link between the system and
nication the program.
The second statement also
Specities the purpose of opening this file. The mode
does this

s
can be one ofthe
job. Mode following:
open the file for reading only.
W open the file for writing only.
open the file for appending (or adding)data to it.

Note that both the filename and mode are specified as strings.They should be enelosed in
double quotation marks.
When trying to open a file, one of the following things may happen:
1. When the mode is writing, a fle with the specifed name is created if the file does not
exist. The contents are deleted, if the file
already exists.
2. When the purpose is'appending,the file is opened with the current contents Sate.
file with the specified name is created if the file does not exist.

3. If the purpose is reading, and if it exists, then the fle is opened with the current
contents safe otherwise an error occurs.

Consider the following statements:

FILE *pl, *p2;


pl = fopen ("data", "r");
p2 = fopen("results", "w"):

The file data is opened for reading and results is opened for writing. In case, the results
fle already exists, its contents are deleted and the file is opened as a new file. If data file
does not exist, an error will occur.
Many recent compilers include additional modes of operation. They include:
r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
We can open and use a number of files at a time. This number however depends on the
Systen we use.

12.3 CLOSING A FILE

A file must be closed as soon as all operations on


have been completed. This ensures that
it

all outstanding information associated with the file is flushed out from the buffers and all

links to the fle are broken. It also prevents any accidental misuse of the file. In case, there is

a limit to the number of files that can be kept open simultaneously, closing of unwanted files
might help open the required files. Another instance where we have to close a fle is when we
want to reopen the same file in a different mode. "The 1/0 library supports a function to do
this for us. It takes the following form:
P)
Sclose(tile,pointen):)
C
392 Programming in ANSI

FILE pointer file_pointer. Look at the f

This would close the file associated with the

lowing segment of a program.

FILE *p,, *P2i


pl = fopen ("INPUT", "w") ;
"r");
p2 = fopen ("OUTPUT",

fclose(p1):
fclose(p2) ;
them after all operations on them are completed
This program opens two files and closes
Once a file is closed, its file pointer can be reused for another
file.

whenever a program terminates


As a matter of fact all files are closed automatically
done with it is a good programming habit.
However, closing a file as soon as you are

I2.4 INPUTIOUTPUT OPERATIONS ON FILES

Once a accomplished using the standard J/o


opened, reading out of or writing to
file it is

routines that are listed in Table 12.1.

The getc and putc Functions


The simplest file gete and
VO function pute.These are analogous togetcharand
are
putchar functions and handle one character at a time. Assume that a file is opened with
mode wand file pointer fpl.Then, the statement
(
putc (c, fp1) :)
writes the character contained, in the character variable e to the file associated with FILE
pointer fpl. Similarly, gete is used to read a character from a file that has been opened in

read mode. For example, thestatemnent

getc (fp2); )
would read a character from the file whose file pointer is fp2.
The file pointer moves by one character position for every operation ofgete or pute. The
gete will return an end-of-file marker EOF, when end of the file has been reached. There
fore, the reading should be terminated when EOF is encountered.

Example 12.1 Write a program to read data from the keybOard, write it to a file called
INPUT, again read the same data from the INPUT file, and
display on it
the screen.
A program and the related input and output data are shown in Fig.12.1.
data via the keyboard and the program writes
enter the inputWe
it, character by character, to the
The end of the data is indicated by file INPUT.
entering an EOF
character, which is control-Z in the
reference system. (This may be
control-D in other systems.) The file
signal. INPUT is closed at this
The getw and putw Functions
gete and pute
functions. They are similar to the
The getw and putw are integer-oriented These functions would be usef
read and write integer values.
functions and are used to
data. The general forms of getw
and putw are:
when we deal with only integer

putw (integer, fp);

getw(fp):
Example 12.2 illustrates the use of putw and getw functions.

named DATA COntains a series of integer numbers.Code a prom


Example 12.2 A file
'odd' numbers to a file t
gram to read these numbers and then write all
be called ODD and all 'even'numbers to a file to
be called EVEN.

in Fig. 12.2. It uses three files simnultaneously and therefore,


we nee
The program is shown
to define three-file pointers f1, f2 and f3.
read fro
First, the file DATA containing integer values is created. The integer values are
the terminal and are written to the file DATA with the help of the statement

putw(number, fl);
file is closed. The n
Notice that when we type -1, the reading is terminated and the
step is to open all the three files, DATA for reading, ODID
and EVEN for writing. T
contents of DATA file are read, integer by integer, by the function getw(fl) and written
ODD or EVEN file after an appropriate test. Note that the statement
(number= getw(r1)) != EOF
reads a value, assigns the same to number, and then tests for the end-of-file mark.
Finally, the program displays the contents ofODD and EVEN files. It is important to r
that thefles ODDand EVEN opened for writing are closed before they are reopened
reading.
he fprinurfand fseanfFunctions
So far, wve have seen functions, that can handle only one character or integer at a time, M..
compilers support two other functions, namely fprintf and fscanf, that can handle a re
of mixed data simultaneously.

The functions fprintf and fseanf perform I/0 operations that areidentical to the famil.
prìntf and scanf unctions, except ocourse thatthey work on files.The first argumeni
these funetions is a file pointer which specifies the file tobe used. The general form offprint

"control string", list):)

where fp is a file pointer associated witha file that has been opened for writing. The contral
string containsoutput specifications for the items in the list. The list may include variables
constantsand strings.Example:
fprintf(fl, "$s kd f", name, age, 7.5);

Here, name is an array variable of typechar and age is an int variable.


The general format of fscanf is
(fBrintp,"control string" list):

Thisstatementwould causethe reading ofthe items in the list from the file specified by fp.
according to the specifications contained in the control string. Example:
fscanf(f2, "s %d", item, &quantity):

Likescanf,fscanf also returns the number ofitems that are successfully read. When the
end offile is reached, it returns the value EOF.

Example 12.3 Write a


program to open a file named INVENTORY and store in it the
following data:
Item name Number Price Quantity
AAA-I 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104
Extend the program to read this data from the file INVENTORY and dis

play the inventory table with the value of each item.


Fig. 12.6 Adding items to an existing file

12.7 COMMAND LINE ARGUMENTS 2mo


What is a command line argumnent? It parameter supplied to a program when the Pro
is a

the program should process. For


gram is invoked. This parameter may represent a filename
to copy the contents of a file named X
FILE to
example, if we want to execute a program
another one named Y_FILE,then we may use a commnand
line like
406| Programning in ANSI C

C> PROGRAM X_ FILE Y_FILE


where PROGRAM is the filename where the executable code of the program is stored.This
eliminates the need for the program to request the user to enter the filenames during exec.
tion. How do these parameters get into the program?
We know that every C program should have one main function and that it marks the
beginning of the program. But what we have not mentioned so far is that it can also take
arguments like other functions.In fact main can take two arguments called argc and arpy
and the information contained in the command line is passed on to the program through
these arguments, when main is called up by the system.
The variable argc is an argument counter that counts the number of arguments on the
command line. The argyis an argument vector and represents an array of character point.
ers that point to the command line arguments. The size of this array will be equal to the
value of argc. For instance,for the command line given above, argc is threeand argv is an
array of three pointers to strings as shown below:
argv[0] -> PROGRAM
argv[l]>X FILE
argv[2]>Y FILE
In order to access the command line arguments, we must declare the main function and
its parameters as follows:

main(int arge,
char *argvrf)up

The first parameter in the command line is always the program name and therefore
argv[0] always represents the program name.

Example 12.7 Write a program that receive a filename and a line


will of text as com
mand line arguments and write the text to the file.

Figure 12.7 shows the use of command line arguments. The command line is
7
F12 TEXT AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG
Each word in the command line is an argument to the main and therefore the total
number of arguments is 9.
The argument vector argv[1] points to the string TEXT and therefore the statenent
fp = fopen(argv[1], "w"):
opens a file with the name TEXT. The for loop that follows immediately writes the remain
ing 7
arguments to the file TEXT.

Program
#include <stdio.h>

main(int arge, char *argv[I)

FILE *fp:
int i;
char word[15]:
File
Management in C 407

fp fopen (argv[1], "w"): /* open


file with name argv]
printf("\nNo. of argments in Command
line
for(i = 2; i < argc; it+) sd\n\n",arg*
fprintf(fp, "%s ", argv[i]):
fclose(fp);
*
write to file argv137

* Writing content of the file to screen

printf("Contents of %s file\n\n", argv[1]):


fp = fopen(argv[1], "r"):
for(i = 2; i < argc; i++)

fscanf (fp,"s", wOrd) ;


printf("s ", word);

fclose(fp):
printf("\n\n"):

/* Writing the arguments from memory */

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


printf ("*s \n", i*5,arg[i]) ;

Output
EEEEEE FFFFFF GGGGG
CCCCCC DDDDDD
C>F12 7 TEXT AAAAAA BBBBBB
9
of arguments in Command line
No.

file
Contents of TEXT
FFFFFF GGGGGG
AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE

C:\C\F12 7.EXE
TEXT
AAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE
FFFFFF
GGGGGG

command line arguments


Fig. 12.7 Use of

You might also like