You are on page 1of 100

Overview of C

for

NTP

1007v1.1 - CW1 1
Overview of C - Session 1
OBJECTIVE:
Participants will be able to
recapitulate their knowledge
of C Programming.

SCOPE:
Salient features of C
programming are covered .

1007v1.1 - CW1 2
Overview of C - Session 1
Books Recommended

 Programming in ANSI C by
E. Balagurusamy (TMH).
 The Programming
Language C by Kernighan
and Ritchie, PHI.

1007v1.1 - CW1 3
Overview of C - Session 1
Overview of C
 Overview of a C Program
 C Elements & Operators
 Control Flow Statements
 Pointers to
Simple Variables
Arrays
Structures
Character arrays
 Creation of Dynamic variables
1007v1.1 - CW1 4
Overview of C - Session 1
Overview of C Contd.
 C Functions
Call by Value
Call by Reference
Program variables
• Scope and Longevity
Function arguments
• Pointers to Pointers
• Functions
 File Management in C
 Command Line Arguments
 C Preprocessor
1007v1.1 - CW1 5
Overview of C - Session 1
Overview of a C Program
 Every C program contains one
or more C functions in
one/more C source files.
 One function named main is
where program execution
always begins. It can be
located anywhere, need not
be the first one.
 Each source file is compiled
separately.
1007v1.1 - CW1 6
Overview of C - Session 1
Overview of a C Program Contd.
 Then all are linked together to form
an executable program.
 Include files are used for external
references of declarations or
functions contained in some other
source file.
 There is no block structure unlike
Pascal. All functions are declared at
the same level.

1007v1.1 - CW1 7
Overview of C - Session 1
Overview of a C Program Contd.
main( ) /*The main function*/
{ …….;
fun_1( );
……;
fun_2( );
……;
} /* end of main */
fun_1( ) /*function fun_1*/
{……;
fun_3( );
} /*end of fun_1 */

Main Source File of a C Program

1007v1.1 - CW1 8
Overview of C - Session 1
Overview of a C Program Contd.

fun_2( ) /*function fun_2 */


{…;
} /*end of fun_2 */
fun_3( ) /*function fun_3 */
{….;
} /*end of fun_3 */

Main Source File of a C Program


(contd.)

1007v1.1 - CW1 9
Overview of C - Session 1
C Elements

RESERVED WORDS (32)


Example: auto, else, sizeof, do,
etc.

 Each reserved is for a specific


purpose.

 May not be used as program


identifier.

1007v1.1 - CW1 10
Overview of C - Session 1
C Elements - Constants
(a) Integers:
DECIMAL: 12345 123L 123U
OCTAL: 012345 0456LU
HEX: 0x12345
 Prefix 0 for octal constant and 0x
for hexadecimal constants.
 Suffix L/l for Long integers,
default: short.
 Suffix U/u for unsigned, default:
signed.
1007v1.1 - CW1 11
Overview of C - Session 1
C Elements - Constants Contd.
(b)Character Constants:

 Delimited by single quotes: ‘x’


 Some pre-defined character
constants:
newline: \n
backslash: \\
single quote: \’
hex number: \xhh

1007v1.1 - CW1 12
Overview of C - Session 1
C Elements - Constants Contd.
(c) String Constants:
 Sequence of characters
delimited by double quotes
such as “This is a string”.
 Represented internally as
array of characters terminated
by the null character ‘\0’

1007v1.1 - CW1 13
Overview of C - Session 1
C Elements - Constants Contd.

(d) Floating Point Constants:


567.89E-6
234e+16
234.78E10f
4561.67E23L
Suffix f/F for float, l/L for long
double, default: double

1007v1.1 - CW1 14
Overview of C - Session 1
C Elements - Constants Contd.
(e) Enumeration Constants:
 Declared when defining an
enumeration.
 enum boolean {FALSE, TRUE};
Internally false/true are assigned 0/1.
 enum days {Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday};
Week days are constants of
enumeration type and are internally
associated with integer values 0, 1, 2,
… 6.

1007v1.1 - CW1 15
Overview of C - Session 1
C Elements - Constants Contd.

(f) Symbolic Constants:


 Handled by C Preprocessor.
 Defined using the #define construct.
 Enable changes with minimal effort.
Example:#define SUNDAY 0
#define MONDAY 1 etc.
The same has been done before as
enumeration constants for all the week
days.

1007v1.1 - CW1 16
Overview of C - Session 1
C Elements - Constants Contd.

g) Declared Constants:
 Declared by the const
qualifier for variable of any
type.
 The value of the variable
cannot be modified.
const float pi = 3.1416;
1007v1.1 - CW1 17
Overview of C - Session 1
Types and Declarations
(a) Basic Types:
void: Special Type
char Single byte ,signed/unsigned.
int Implementation dependent size
signed/unsigned, short or long.
float single-precision real
Double double-precision real
Type qualifier long can be applied to
double to specify extended precision.

1007v1.1 - CW1 18
Overview of C - Session 1
Types and Declarations Contd.

(b) Arrays:
 C allows multidimensional arrays.
 Arrays in C are indexed from 0.
Example:
int A[10][10];
First element: A[0][0]
Last element: A[9][9]
size = 100 elements

1007v1.1 - CW1 19
Overview of C - Session 1
Types and Declarations Contd.
( c) Enumeration:
 Provide a method of associating a constant
set of values starting from zero to a set of
identifiers automatically.
 Advantage over #define:
Automatic generation of constant values.
Example
enum days {Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday };
enum days workingday, holiday;

1007v1.1 - CW1 20
Overview of C - Session 1
Types and Declarations Contd.
(d) Structures:
#define MAXSZ 100
struct list_tag {int count,entry
[MAXSZ];};
struct list_tag list, *listptr;
Access of individual parts of a
structure:
(i) list.count, list.entry[5]
(ii)Use -> instead of dot when de-
referencing a pointer to a structure.

1007v1.1 - CW1 21
Overview of C - Session 1
Types and Declarations Contd.

Bit Fields:
struct person{char name[10],
address[20]; unsigned sex:1,
age:7;} emp[100];
Here the last byte of structure
person will contain:
* 1 bit for sex (0 or 1), and a
* 7-bit unsigned field to store age
<= 27-1

1007v1.1 - CW1 22
Overview of C - Session 1
Types and Declarations Contd.
(e) Unions:
 These are variant structures of C.
 Similar to structures except that only
one member of union is active at a time.
 Different members of a union are
distinguished by a tag field.
 It is programmer’s responsibility to
keep track of which member is currently
being used.

1007v1.1 - CW1 23
Overview of C - Session 1
Union: Example
To compute the area, volume and
circumference of geometrical
figures

enum shape_tag{CIRCLE,
RECTANGLE, TRIANGLE};
enum triangle_tag
{EQUILATERAL, ISOSCELES,
SCALENE};

1007v1.1 - CW1 24
Overview of C - Session 1
Union: Example Contd.
typedef struct figure_tag
{float area,volume,circumfernce, height;
enum shape_tag shape;
union
{float radius;/*First variant for Circle*/
struct { float length, width;
enum boolean_tag square;} rectangle;
struct {float side1, side2, side3;
enum triangle_tag kind;} triangle;}u;
} Figure_type;

1007v1.1 - CW1 25
Overview of C - Session 1
Union: Example Contd.

1 area area area


2 volume volume volume
3
circumference circumference circumference
4 height height height
t
shape = circle shape = rectangle shape = triangle
5
radius length side1
6
7 width side2
8 unused square side3
unused kind

1007v1.1 - CW1 26
Overview of C - Session 1
Advantages of Union

 They clarify logic of the program.


 Same space can be assigned for
all members of a union as only
one member is usable at a time.
 Space allocated for the union is
just the amount needed by its
largest member.

1007v1.1 - CW1 27
Overview of C - Session 1
Naming a Type: typedef
(f) Typedef:
 A structure can be given a name.:
typedef struct list_tag List_type;
 Now a variable of this structure type
can be declared as:
List_type list; instead of struct
list_tag list;
(though both are equivalent)
 We could have defined the structure
and the type at the same time as:
typedef struct list_tag
{int count, entry[MAXSZ];}List_type;
 The list_tag is optional in above
declaration.
1007v1.1 - CW1 28
Overview of C - Session 1
C Operators
Order Associativity

1. Function Call: ( ) L to R

Array Element Reference: [ ]


Pointer to Structure de-reference : ->
Structure de-reference: .

1007v1.1 - CW1 29
Overview of C - Session 1
C Operators Contd.
Order Associativity
2. Logical NOT: ! R to L
Ones Complement: ~
Arithmetic Unary: ++ -- + -
Pointer Reference (Indirection): *
Address of: &
Type cast conversion: (type)
Size of an object: sizeof
3. Arithmetic Binary: * / % L to R
4. Arithmetic Binary: + - L to R

1007v1.1 - CW1 30
Overview of C - Session 1
C Operators Contd.
Order Associativity
5. Bitwise left/right shifts: << >> L to R
6. Relational: < <= > >= L to R
7. Relational: == != L to R
8. Bitwise AND: & L to R
9. Bitwise XOR: ^ L to R
10.Bitwise OR: | L to R
11.Logical AND: && L to R
12.Logical OR: || L to R

1007v1.1 - CW1 31
Overview of C - Session 1
C Operators Contd.
Order Associativity
13. Conditional expression: ?: R to L
Example: x = (a > b) ? a : b;
Same as: if (a > b) x=a; else x=b;
14. Assignment: R to L
= += -= *= /= %= &= ^= |= >>= <<=
15. Comma: , L to R
Example: z = (x=10, y=5, x+y);
Value of z = 15, also used in if, for, while.

1007v1.1 - CW1 32
Overview of C - Session 1
Control Flow Statements

(a) If-Else: with else part optional


if (expression) statements
else statements

1007v1.1 - CW1 33
Overview of C - Session 1
Control Flow Statements
(b) Switch: Multiway branch on single
expression.
Switch (expression) {
case constant_expr : statements
case constant_expr : statements
/* as many cases as needed…*/
default: statements }
 It is important to note that the cases
fall through, i.e., execution will
continue to the following case unless
explicit action is taken to leave the
switch.
 Use break as the last action of a case
to leave the switch.
1007v1.1 - CW1 34
Overview of C - Session 1
Control Flow StatementsContd.
( c) Loops:
(i) while (expression) statements
where statements will be executed as long as
expression evaluates to nonzero.
(ii) for (expr1; expr2; expr3) statements
All three expressions are optional but semicolons
are not. The for is equivalent to: expr1;
while (expr2) {statements; expr3;}
(iii) do-while loop
Tests for loop termination at the end.
do statements while (expression);
The loop will be executed at least once.

1007v1.1 - CW1 35
Overview of C - Session 1
Control Flow Statements Contd.
(iv) break for early exit from a loop
The break will cause execution to continue
after the enclosing for, while, do or switch.
(v) continue to skip a part of loop body
The continue will result in skipping the
following statements and continuing the next
iteration of the enclosing for, while, or do
loop to execute.
(vi) goto: It is not looked upon with favor. Can
be used for early exit from a loop and also to
exit a switch instead of a break.

1007v1.1 - CW1 36
Overview of C - Session 1
Pointers to Simple Variables
Example : char *p; char c = ‘a’;
p is a pointer to a character variable.
p = NULL; /* p is a null pointer*/
Address of a simple variable can be obtained by
the unary operator &:
p = &c; /* p contains address of c */
Following declaration does the same:
Char c = ‘a’, *p = &c;

1007v1.1 - CW1 37
Overview of C - Session 1
Pointers to Simple Variables
Contd.

To refer to a value that a pointer


points to:
Use * for pointer indirection: *p =
‘b’;
Type binding of Pointers:
typedef struct nodetag{ …. }
node_type;
node_type *x,*y; char *a,*b;
Then, x = y; a = b; /* is
legal.*/
x=a; /* is illegal.*/
1007v1.1 - CW1 38
Overview of C - Session 1
Pointers to Arrays
 Declare a 1-dimensional array
of integers and its pointer:
int a[10], *q = a;

 *q points to a[0]. *q++ points


to a[1] which could be 2 or 4
bytes away depending on the
hardware.

1007v1.1 - CW1 39
Overview of C - Session 1
Pointers to Arrays Contd.
 Declare a 2-d array of integers and its pointer:
int b[ ][4] ={{75, 27, 11, 35}, {22,19, 30, 8}, {40, 5, 90,
13}}, *p = b;
75 27 11 35
The matrix b: 22 19 30 08
40 05 90 13
 p: Pointer to 1st row, p+i : Pointer to ith row,
 *(p+i) : Pointer to 1st element in ith row,
 *(p+i)+j : Pointer to jth element in ith row,
 *(*(p+i)+j) : element a[i][j] same as *(*(b+i)+j)

1007v1.1 - CW1 40
Overview of C - Session 1
Pointers to Arrays Contd.
Example: Operations on pointers to
arrays.
Note: ptr is a pointer to an array with
each row containing 3 elements.

#include “stdio.h”
int a[]
[3]={30,40,50,33,44,55,21,31,41};
void main (void)
{int j,k, (*ptr)[3]=a;

1007v1.1 - CW1 41
Overview of C - Session 1
Pointers to Arrays Contd.
for ( j = 0 ; j < 3; j++)
{ printf(“\nptr=%u\n”, ptr);
printf(“address\tvalue\n”);
for (k=0; k<3; k++)
printf(“%u\t\t%u\n”,*ptr+k,
*(*ptr+k));
ptr++;} Program Output
} ptr=100
address value
100 30
102 40
104 50
1007v1.1 - CW1 42
Overview of C - Session 1
Pointers to Arrays Contd.

Program Output
ptr=106
address value
106 33
108 44
110 55
ptr=112
address value
112 21
114 31
116 41
1007v1.1 - CW1 43
Overview of C - Session 1
Pointers to Arrays Contd.
Operations on Pointers
 Note that if we increment i by 1, p is
incremented by 4, the size of each row.
 Integer expression can be added to or
subtracted from a pointer.
 Two pointers can be compared if they
point to the same array. Otherwise the
comparison is not meaningful.
 When handling arrays, use pointer
access method instead of indexing
which is much slower.

1007v1.1 - CW1 44
Overview of C - Session 1
Pointers to structures

 Declare an array of structures and


then use a pointer to its first
element:

struct s_tag{char c; int i;} x[10], *p;


p = x; p->c = ‘a’; p->i = 0; p++;
p->c=‘b’; /*-> pointer de-
referencing*/

1007v1.1 - CW1 45
Overview of C - Session 1
Pointers to Character Arrays
Contd.
One Dimensional Character Arrays
char line[100], *p;
Let p point to start of array: p=&line[0];
 Array name is synonym for its starting address:
p = line; /* same as above */
 Perform the assignments: *p = ‘a’; and
*(p+1) = ‘b’; /*p points to start of line */
 Do the same by pointer incrementing:
*p++ = ‘a’; *p++ = ‘b’;
Now p points to line[2]. This is equivalent to:
line[0] = ‘a’; line[1] = ‘b’;
 Difference between *p[3] and (*p)[3]:
Array of 3 pointers - Pointer to an array with
each row containing 3 elements.

1007v1.1 - CW1 46
Overview of C - Session 1
Pointers to Character Arrays
Contd.
Two Dimensional Character Arrays
 Declare a 2-d array to store 3 names:
char name1[3][12];
Three rows, each stores a name 12 char long
(including null char). Total storage
requirements = 36 bytes.
 Ragged Arrays:
Rarely individual strings will be of equal
length. Instead of making each row of fixed
number of chars, make it a pointer to a string
of varying length (total bytes used now = 28).
char *name2[3] = {“New
Zealand”,“Australia”,“India”};
Here name2 is an array of 3 pointers, each
pointing to a particular string.
Accessing jth character in ith string: *(name
2[i] + j)
1007v1.1 - CW1 47
Overview of C - Session 1
Creation of Dynamic Variables
 Declare the pointer variable p as:
node_type p;
 malloc( ) allocates a block of
memory of size of node_type node:
p = (node_type * ) malloc ( sizeof
(node_type));
p = pointer returned for the
storage area of type node_type.
 sizeof(node_type) returns the
number of bytes occupied by a
variable of type node_type.
 free(p) ; returns the space used
by the dynamic variable.
1007v1.1 - CW1 48
Overview of C - Session 1
Functions
 A task is broken into separate
functions in modular programming
because it is easier to deal .
 The main program called main is a
function which may invoke other
functions.
 The information passed to a function is
called an argument.
 The information received by the
function is called a parameter.

1007v1.1 - CW1 49
Overview of C - Session 1
Functions Contd.
 Function prototype: a concise
way of describing the number
and type of arguments a
function expects and what the
function returns.
 Void is used in parentheses if
function does not expect any
arguments.
 The type in front of function
name indicates the type of the
value returned.
1007v1.1 - CW1 50
Overview of C - Session 1
Arguments to Functions
Call by Value:
void f(int k)
{ k - -;
printf(“k is %d\n”, k);
}
Call by reference
void g(int *k)
{ *k = 4;
}

1007v1.1 - CW1 51
Overview of C - Session 1
Arguments to Functions
Contd.
The Caller Functions
void caller1(void)
{ int i = 10;
printf(“i = %d\n”, i);
f(i);
printf(“i = %d\n”, i);
}
void caller2(void)
{ int i = 10;
printf(“i = %d\n”, i);
g(&i);
printf(“i = %d\n”, i);
}
1007v1.1 - CW1 52
Overview of C - Session 1
Arguments to Functions
Contd.

Result of Executing Caller1


i = 10 k is 9 i = 10 (Call by value)
Result of Executing Caller2
i = 10 i = 4 (Call by reference)

NOTE:
Arrays are always passed by
reference.

1007v1.1 - CW1 53
Overview of C - Session 1
Function Prototypes and Include
Files
 function prototype is a declaration of a function type
(what it returns) and the number and type of
arguments: void f(int);
is the function prototype for function f. It expects one
argument of type int and it does not return any value.
 Standard Library Functions:
They have their prototypes in *.h files where * denotes
a name available with a compiler. Function strcpy and
so many string processing functions have their
prototypes in the file string.h. So we include this file in
the program as:
#include <string.h> /*Angular brackets*/
 Other *.h files that we create are in current directory
and their names are enclosed in double quotes.

1007v1.1 - CW1 54
Overview of C - Session 1
Program Variables
 Variables in C differ in behavior from those
in most other languages. It all depends on
the storage class a variable may assume.
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
We will discuss scope and longevity of these
4 storage classes of variables.
 Scope determines over what part(s) of the
program a variable is actually available for
use (active).
 Longevity refers to the period during which
a variable retains a value.

1007v1.1 - CW1 55
Overview of C - Session 1
Program Variables Contd.
Depending on their place of
declaration, variables may also
be classified as:

Internal or Local :
Declared within a particular
function.

External or Global:
Declared outside of any function.

1007v1.1 - CW1 56
Overview of C - Session 1
Automatic Variables
 It is the class of a variable by default.
 They are declared within a function, and
known as internal or local variables.
 They are created when the function is
called and destroyed automatically when
the function is exited. Therefore their
scope and lifetime is the body of the
function.
 They can also be defined within a set of
braces known as “blocks” and are
meaningful only there.
 Locals can have same names, but they are
distinct variables in their region.

1007v1.1 - CW1 57
Overview of C - Session 1
Automatic Variables Contd.
main()
{ int n=80;
If (n <= 100)
{int n=5, sum;
printf(“ n=%d, “, n)
}; /* sum is valid only within
braces*/
function2();
printf(“ %d\n“, n);
}
function1()
{int n=10;
printf(“ %d, “, n);
}
function2()
{int n= 100;
function1();
printf(“ %d, “, n);
} /* Output: n=5 10 100 80 */
1007v1.1 - CW1 58
Overview of C - Session 1
External Variables
 They are global variables that are both alive
and active through out the

entire program.
 They are declared in the beginning of a source
program outside any function and initialized to
zero by default.
 Multiple source files of a program can share a
variable if it is declared as extern in all those
files and defined in exactly one (usually the
main) file.

1007v1.1 - CW1 59
Overview of C - Session 1
External Variables Contd.

 Any local variable with the same name


as that of a variable in the outer block
overrides that in its lexicographic scope.

 Similarly when a function is defined in


one file and accessed in another, the
later file must include a function
declaration in the beginning. Since
functions are external by default, we do
so without the qualifier extern.

1007v1.1 - CW1 60
Overview of C - Session 1
Static Variables
 As the name suggests their longevity
is through out the lifetime of a
program.
 They may be either internal or
external type depending on the place
of declaration:
 Internal Static variables are declared
inside a function. Like auto variables,
their scope extends the body of the
function, except that they are alive
through out program execution.

1007v1.1 - CW1 61
Overview of C - Session 1
Static Variables Contd.
main() /*Example of Internal */
{ int k; /* Static Variables */
for (k=1; k<=3; k++) funstatvar();
}
void funstatvar(void)
{static int n = 0; /* n remembers
its */
n = n + 1; /* value during calls
*/
printf(“ n = %d “, n);
}
output: n = 1 n = 2 n = 3

1007v1.1 - CW1 62
Overview of C - Session 1
Static Variables Contd.
 Static variables are initialized only once
when the program is compiled.
External static variable are declared
outside of all the functions in a program.
 The difference between a static external
variable and a simple external variable is
that the former is available only within the
source file where it is defined while the
later can be accessed by other files also
which contain its extern declaration.
 For example, an external static variable
defined in a source file can be used to
count the number of calls to any functions
defined in that file.

1007v1.1 - CW1 63
Overview of C - Session 1
Register Variables

Frequently accessed variables


can be kept in machine
registers for faster execution
of programs.

Example
register int count;

1007v1.1 - CW1 64
Overview of C - Session 1
Auto/Static/External Variables
Example of a multi-file C program
file1.c file2.c
void func1() extern int m;
void func2() static int count = m;
void func3() func2()
int m; /* global */ { int k;
main() k = m; count ++;
{int k = m; printf{“k=%d“, k);}
m = m + 1; func3()
func1();func2();{ count ++;
func3(); func1(); printf(“count=
printf(“m=%d %d”, count);}
k=%d\n”, m, k);}

1007v1.1 - CW1 65
Overview of C - Session 1
Auto/Static/External Variables
Example of a multi-file C program
file1.c

func1()
{static int j = 1;
m = m + 1;
printf(“j=%d “, ++j);
}

RESULTS:
j=2 k=2 count=2 j=3 m=3
k=0
1007v1.1 - CW1 66
Overview of C - Session 1
Pointer to Function as Argument
 A function has an address location in memory just
like a variable. A pointer to a function is declared
as:
type (*funptr)();
type is the type of value returned by the function,
funptr is the pointer to the function.
Example:
#include <math.h>
#define pi = 3.14159
main() /* main */
{double y(double);
double table(double(*)(), double, double, double)
printf(“Table of Y(x) = 2x2-x+1\n”);
table(y, 0.0, 1.0, 0.5);
printf(“Table of cos(x)\n”);
table(cos, 0.0, 1.0, 0.5); } /* end of main*/

1007v1.1 - CW1 67
Overview of C - Session 1
Pointer to Function as Argument
Contd.
double y(double x)
{return(2*x*x-x+1);}
double table(double (*f)(), initval, lastval, step)
{double a, value;
for(a=initval; a<=lastval; a+=step)
value = (*f)(a); /* y/cos replaces *f */
printf(“%5.1f%10.4F\n”, a, value);
}

1007v1.1 - CW1 68
Overview of C - Session 1
Pointer to Function as Argument
Contd.
RESULTS

Table of Y(x) = 2x2-x+1


0.0 1.0000
0.5 1.0000
1.0 2.0000

Table of cos(x)
0.0 1.0000
0.5 0.8776
1.0 0.5403

1007v1.1 - CW1 69
Overview of C - Session 1
Pointer to Pointer as Argument
Contd.
 We invoke a function f that
modifies whatever the pointer p
points at:
void f(char *);
void main(void)
{char c=‘b’; f(&c);}
void f(char *p) {*p = ‘a’;}
 What if we want to modify the
pointer itself, instead of what it
points to?
1007v1.1 - CW1 70
Overview of C - Session 1
Pointer to Pointer as Argument
Contd.
 Then pass pointer by reference.
void g(char **);
void main(void) /*main */
{char line[10]={‘a’,’b’,’c’,’d’,’e’,’f’,
‘g’,’h’,’I’,’j’}, *p = line;
for(int j=0; j<10; g(&p))
printf(“%s”, *p);} /end of main*/
void g(char **ptr) {(*ptr)++;}

Result: abcdefghij

1007v1.1 - CW1 71
Overview of C - Session 1
Functions that return a Pointer
 If each node of a linked list is defined as:
typedef struct node_tag
{float info;struct node_tag *next;}
node_type;
 We can write a function makenode which
creates such a node and returns a pointer to
the new node:
node_type *makenode(float item)
{node_type *p;
if ((p = (node_type *) malloc
(sizeof(node_type))) != NULL)
p -> info = item;
return p;}
1007v1.1 - CW1 72
Overview of C - Session 1
File Management in C
Why File Management is important?
 Until now we have used I/o functions
like scanf and printf to read/write data
from/to keyboard/screen.
 This works fine for small data.
 It is cumbersome and time consuming to
handle large volumes of data the same
way.
 Further one cannot afford to lose
volumes of data on program termination
or when computer is turned off.

1007v1.1 - CW1 73
Overview of C - Session 1
File Management in C Contd.
 Therefore more flexible approach is
needed by storing data on hard disk to
overcome the said problems.
 There are two distinct ways to do I/O in
C:
* Low-level I/O using UNIX system calls
* High-level I/O using functions of
standard I/O library of C
 We shall discuss the later scheme and
use the following functions:

1007v1.1 - CW1 74
Overview of C - Session 1
File Management Functions

* fopen() : Create new or open an existing file


* fclose() : Close an opened file
* getc() : Read a char from a file
* putc() : Write a char to a file
* fprintf() : Write a set of values to file
* fscanf() : Read a set of values from file
* getw() : Read an integer from a file
* putw(): Write an integer to a file
* fseek() : Set position to a desired point in
file
* ftell() : Give current position in file
(in bytes from start)
* rewind() : Set position to beginning of file
* fread() and fwrite() for group read/write

1007v1.1 - CW1 75
Overview of C - Session 1
Example: File Management
/* Handling of Characters, Integers
and Mixed Data Values */
#include <stdio.h>
main()
➜ {FILE *fp; /* file type pointer */
int n, j; long m;
char c, filename[10];
struct item_rec {char name[10];
int number; float price;} item;
➔ printf(“Type File_Name: “);
➔ scanf(“%s”, filename);
➔ fp = fopen(filename, “w”);
1007v1.1 - CW1 76
Overview of C - Session 1
Example: File Management
Contd.
/* get a char from keyboard & write to the
file on disk */
printf(“\nCharacter_Input:\n”);
while ((c=getchar())!= EOF)
➔ putc(c, fp);
➔ fclose(fp);
/* Read a character from the disk file and
display on screen */
fp = fopen(filename, “r”);
printf(“\nCharacter Output: “);
➔ while ((c = getc(fp)) != EOF)
printf(“%c”,c);
fclose(fp);
1007v1.1 - CW1 77
Overview of C - Session 1
Example: File Management
Contd.
/* Read an int from the keyboard & write onto
disk file */
fp = fopen(filename, “w”);
printf(“\nInteger_Input:\n”);
for (j=1; j<=20; j++)
{scanf(“%d”,&n);
if (n==-1) break;
➔ putw(n, fp);}
fclose(fp);
/* Read int from the disk file and display it on
screen */
printf(“\nOutput: ”);
fp = fopen(filename, “r”);
➔ while ((n = getw(fp)) != EOF)
printf(“%4d ”, n);
fclose(fp);
1007v1.1 - CW1 78
Overview of C - Session 1
Example: File Management
Contd.
/* Read/write mixed data from/to key-
board/screen and write/read the same
into/from file on disk */
fp = fopen(filename, “w”);
printf(“\nType Inventory Data:”,
“\nItem_name Number Price\n”);
➔ while !feof(stdin)
➔ {fscanf(stdin, “%s %d %f ”, item.name,
&item.number, &item.price);
➔ fprintf(fp, “%s %d %.2f”, item.name,
item.number, item.price);}
➔ m = ftell(fp);
printf(“\nNo. of bytes entered = %d”, m);
fclose(fp);
1007v1.1 - CW1 79
Overview of C - Session 1
Example: File Management
Contd.
printf(“\nItem_name Number Price\n”);
fp = fopen(filename, “r”);
for(j = 1; j<=3; j++)
➔ {fscanf(fp, “%s %d %f “, item.name,
&item.number, &item.price);
➔ fprintf(stdout, “\n%10s %4d %7.2f “,
item.name, item.number, item.price);}
➔ m = ftell(fp)/3;/*size of item_rec*/
➔ fseek(fp, -m, 1); /* position at 3rd record*/
/* from current position*/
fscanf(fp, “%s %d %f “, item.name,
&item.number, &item.price);

1007v1.1 - CW1 80
Overview of C - Session 1
Example: File Management
Contd.
fprintf(stdout, “\n%10s %4d %7.2f “, item.name,
item.number, item.price); /* print 3rd record */
➔ rewind(fp); /* position at start */
fscanf(fp, “%s %d %f “, item.name, &item.number,
&item.price);/*read 1st record */
fprintf(stdout, “\n%10s %4d %7.2f “, item.name,
item.number, item.price); /* print 1st record */
m = m +m +m;
➔ fseek(fp, m, 0) /*position at 4rth*/ fscanf(fp, “%s %d
%f “, item.name, &item.number, &item.price);/*read
last record */
fprintf(stdout, “\n%10s %4d %7.2f “, item.name,
item.number, item.price); /* print last record */
fclose(fp);} /* end of program */

1007v1.1 - CW1 81
Overview of C - Session 1
Command Line Arguments(CLA)
What are these?

 They are parameters supplied to a


program when it is invoked.
 The function main can also take
arguments like other functions. Its
arguments are called:
argc : arguments counter on CLA.
Argv : arguments vector, an array
of character pointers that points to
CLA.

1007v1.1 - CW1 82
Overview of C - Session 1
Command Line Arguments(CLA)
Contd.

 Let’s append our inventory by


more items. We may invoke our
program as follows:
<Append_Inv> <file_name>
where the first argument is the
name of our C program and the
second one is the append file
name.
Then, argc = 2,
argv[0]→<Append_Inv>
and argv[1] → <file_name>.
1007v1.1 - CW1 83
Overview of C - Session 1
Command Line Arguments(CLA)
Contd.
Example: Appending a file
#include <stdio.h>
void main(int argc; char *argv[])
{FILE *fp;
struct item_rec {char name[10];
int number; float price;} item;
fp = fopen(argv[1], “a”);
printf(“\nType data from key-board:”);
printf(“Item_ name Number Value\n”);

1007v1.1 - CW1 84
Overview of C - Session 1
Command Line Arguments(CLA)
Contd.

while !feof(stdin)
{fscanf(stdin, “%s %d %f”, item.name,
&item.number, &item.price);
fprintf(stdout, “%s %d %.2f”,
item.name, item.number, item.value);
fprintf(fp, “%s %d %.2f”, item.name,
item.number, item.value);}
fclose(fp);
} /* end main */

1007v1.1 - CW1 85
Overview of C - Session 1
The C Preprocessor
 It is a program that processes the source code
before it passes through the compiler
 It provides tools normally unavailable in other
high-level languages.
 The tools can be used by programmers to make
the program easy to read and modify, portable
and more efficient.
 The preprocessor operates under the control of
certain directives which are placed before the
function main. All directives begin with the
symbol # in column 1 and do not require
semicolon at the end.

1007v1.1 - CW1 86
Overview of C - Session 1
The C Preprocessor
Contd.

 Directives fall into 3 categories:


* Macro substitution directives
* File inclusion directives
* Compiler control directives

1007v1.1 - CW1 87
Overview of C - Session 1
Macro Substitution

 Is a process where an identifier in a


program is replaced by a predefined string
composed of one or more tokens.
 The task is accomplished under the
direction of #define statement.
 There are 3 different forms of define:
* Simple macro substitution
* Macro substitution with arguments
* Nested macro substitution

1007v1.1 - CW1 88
Overview of C - Session 1
Simple Macro Substitution

#define COUNT 100


#define FALSE 0
#define CAPITAL “Delhi”
#define PI 3.1415926
#define START main(){
#define END }

1007v1.1 - CW1 89
Overview of C - Session 1
Macro Substitution with
Arguments
#define SQUARE(x) (x*x)
 Let’s calculate area now:
area = SQUARE(a+b);
This gets expanded as follows:
area = (a+b*a+b)
which is not what is intended!!

1007v1.1 - CW1 90
Overview of C - Session 1
Macro Substitution with Arguments
Contd.

 So let’s modify the definition by


including parentheses around the
arguments:
#define SQUARE(x) ((x)*(x))
Now we get the correct expansion:
area = ((a+b)*(a+b))

 Note that there should not be any


space between the macro name and
the left parenthesis.

1007v1.1 - CW1 91
Overview of C - Session 1
Nested Macro Substitution
 One predefined macro can be used in
the definition of another macro:
#define QUAD(X)
SQUARE(X)*SQUARE(X))
Now expand QUAD(1+2):
(SQUARE(1+2)*SQUARE(1+2))
= (((1+2)*(1+2))*((1+2)*(1+2))).
 Undefining a Macro
#undef SQUARE
This is useful if we want to restrict
the definition to a particular part of
the program.
1007v1.1 - CW1 92
Overview of C - Session 1
File Inclusion

 An external file containing


functions or macro definitions can
be included as a part of a program:
#include “filename”
 The double quotes are replaced by
angular brackets ‘<‘ and ‘>’ for
including files from the standard
directories:
#include <stdio.h>

1007v1.1 - CW1 93
Overview of C - Session 1
Compiler Control Directives
Following 3 situations may be faced
while developing a large program:
(Discussion is limited to only a few
more common macros)

 We want to be certain whether a


particular macro definition has been
included or not:

* We wish to include it if it is not,


* We wish to delete it if it is there.

1007v1.1 - CW1 94
Overview of C - Session 1
Compiler Control Directives
Contd.
Example
#ifndef TEST or #ifdef TEST
#define TEST 1 #undef TEST
#endif #endif
* define is erroneous if TEST is
already defined.
* Undef is erroneous if TEST is not
defined.

The main concern here is easy


readability and modifiability.

1007v1.1 - CW1 95
Overview of C - Session 1
Compiler Control Directives
Contd.

 Suppose a customer has 2 types of


computers, IBM_PC and HP, and TIL is
required to write a common program
which will run on both systems, though
certain lines of code will be different
for each system:
 The compiler will compile the code for
IBM_PC if this macro is defined.
Otherwise it will compile the code for
HP machine as shown in the following
example program.
The main concern here is to make
program portable.
1007v1.1 - CW1 96
Overview of C - Session 1
Compiler Control Directives
Contd.
Example:
main ()
{…
#ifdef IBM_PC
{…} /* code for IBM_PC */
#else
{…} /* code for HP machine
*/
#endif
…}

1007v1.1 - CW1 97
Overview of C - Session 1
Compiler Control Directives
Contd.

 A large program is in the process of


testing by including print statements at
several places to display intermediate
results. We want these debugging
statements to be part of the program such
that they become ‘active’ only when it is
desired to be so:
 The statements between the directives
ifdef and endif in the following program
are compiled only if the macro DEBUG is
defined. Once everything is o.k., delete or
undefine the macro.

1007v1.1 - CW1 98
Overview of C - Session 1
Compiler Control Directives
Contd.
Example
...
#ifdef DEBUG
printf … /* The main concern
#endif here is conditional
… compilation. */

#ifdef DEBUG
printf …
#endif

1007v1.1 - CW1 99
Overview of C - Session 1
Summary
In this session you have revised:
 Overview of a C Program
 C Elements & Operators
 Control Flow Statements
 Pointers to Simple Variables, Arrays, Structures,
Char arrays;Creation of Dynamic variables.
 C Functions
Call by Value and Reference,
Program variables: Scope and Longevity,
Pointers to Pointers and functions as
arguments.
 File Management in C
 Command line arguments.
 C Preprocessor

1007v1.1 - CW1 100


Overview of C - Session 1