0% found this document useful (0 votes)
9 views61 pages

CC 1202 Computer Programming 2 Final

Uploaded by

Emjay Deleon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views61 pages

CC 1202 Computer Programming 2 Final

Uploaded by

Emjay Deleon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 61

Computer Programming 2

(Intermediate Programming)

Nomer B. Aguado
Table of Contents

Module 9: POINTERS
Introduction 107
Lesson 1. Introduction to Pointers 108
Lesson 2. Declaration and Initialization of Pointers 113
Lesson 3. Pointers Arithmetic 117
Lesson 4. Pointers and Functions 123
Lesson 4.1 Call by Reference 125
Lesson 4.2 Pointers to Functions 130
Lesson 5. Pointers and Arrays 131
Lesson 5.1 Pointers to One-Dimensional Arrays 131
Lesson 5.2 Pointers to Two-Dimensional Arrays 134
Lesson 5.3 Pointers and Strings 135

Assessment Task 138


Summary 139
REFERENCES 139

Module 10: BASICS OF FILE HANDLING


Introduction 140
Lesson 1. File Handling 141
Lesson 2. Different File Types in C 142
Lesson 3. Opening a Text File in C 143
Lesson 4. Closing a Text File in C 144
Lesson 5. Reading and Writing a Text File in C 145
Lesson 6. Reading and Writing a Binary File in C 147

Assessment Task 150


Summary 151
REFERENCES 151

Module 11: FILE HANDLING FUNCTIONS


Introduction 152
Lesson 1. Reading from a File 153
Lesson 2. Writing into a File 156
Lesson 3. Closing a File 158
Lesson 4. Cursor Positioning Functions in Files 159

Assessment Task 161


Summary 162
REFERENCES 163

ii
List of Tables

Table Description

9.4 Pointers 111


9.5 Data Types and Sizes 119
10.6 File Modes 144

iii
List of Figures

Figure Description

9.25 Address of Array Elements 132


9.26 Accessing Elements of a 2-D Dimensional Array 135

iv
MODULE 9

POINTERS

Introduction

The memory of our computer can be considered as succession of memory cells


and each one of them has a unique address so that it can be easily located in memory.
Pointers in C are basically used to access the value of a variable residing on a particular
memory cell. Pointers, or simply a pointer variable, can be defined as a variable which
contains or stores the address of another variable in memory. A pointer is considered to
be a very powerful feature of C programming language which has use in advancing
programming as C pointers can be used to any variable type of C (Codewithc.com, 2014).

Learning Outcomes

At the end of this module, students should be able to:

• Discuss what is pointers and explain how to declare pointers and their usage to
access variable values.
• Use pointers with arithmetic.
• Apply the usage of pointers with functions, arrays and strings.

Lesson 1. Introduction to Pointers (Tilak Maharashtra Vidyapeeth,


n.d.)

107
Based in the article “C Programming” by Tilak Maharashtra Vidyapeeth (n.d),
Pointers are an important feature of the C language. To understand pointers let us revise
certain points about computer memory. You already know that computers store the data
and instructions in memory. The computer’s memory is a sequential collection of storage
cells. Each cell is known as a byte of memory. Each cell also has a unique address
associated with it. This address is a number. Generally, the addresses given to memory
locations are numbered sequentially.

Whenever a variable is declared in a program, the system allocates memory to


hold the value of the variable. Each byte has a unique memory address; therefore, each
variable also has a unique address associated with it.

Example:

int i = 10;

This declaration reserves space in memory to store the value of the variable i. The name
i gets associated with that particular memory address. The value 10 which has been
assigned to the variable i gets stored in that particular memory location. We can represent
the location of the variable in memory as follows:

Variable Name = i
Value = 10
Address = 3245

Let us assume that the computer has allocated the address location 3245 to store the
value of the integer variable i. Thus, the variable i gets an address associated with it to
store its value. It is possible for us to determine the address of a variable in memory. It
can be done as follows:

Example: To determine the address of a variable in memory.

108
main()
{

int i = 10;
printf(“\nValue of I :”, i);
printf(“\nAddress of i:” &i);

Output:

Value of I: 10
Address of I: 3245

It is clear from the above example that the address of i is obtained with the
expression &i. We make use of the address operator (&) to determine the address of
the variable i. Thus, the memory address of a variable is a number which is always
positive. Since the memory address is a number we can as well store it in memory like any
other variable. This is where pointers come into picture. In all the programs we have
written so far, we have made use of the address operator & when using scanf to read
the values of the variables. The same address operator can be used to determine the
address of the corresponding variable in memory.

Thus, pointers are nothing but variables used to hold memory address. A pointer is a
variable which contains the address of another variable. It is therefore possible to access
the value of a variable either with the help of the variable name or with its address.

Let us write a program to further understand the concept of pointers

Example:

main()
{

109
int a;
char ch1;
float b;
a = 100;
ch1 = ‘Z’;
b = 40.85;

printf(“\nThe value of a is %d:”, a);


printf(“\nThe address of a is :”, &a);
printf(“\nThe value of ch1 is %c:”, ch1);
printf(“\nThe address of ch1 is :”, &ch1);
printf(“\nThe value of b is %f:”, b);
printf(“\nThe address of b is :”, &b);

Output:

The value of a is: 100


The address of a is: 6540
The value of ch1 is: Z
The address of ch1 is: 3400
The value of b is: 40.85
The address of b is: 5284

Note: It is important to note here that the addresses of the variables that are output here
may not match with the output you get and that every time you run this program, the
compiler may assign different memory locations to the variables and you may get different
addresses. We can also make use of the %u operator to print addresses since
addresses are unsigned integers.

Since the address of a variable is a number we can as well store it in another variable. Let
us use a variable j to store the address of the variable i.

The address of i can be stored in j as:

110
j = &i

But every variable in C has to be declared before we can use it. Since we are using j for
the purpose of storing the address of i we can make use of the dereference operator (*)
to declare it. The dereference operator operates on a pointer variable, and returns a value
equivalent to the value at the pointer address.

We declare j as follows:

int*j;

This declaration tells the compiler that j is a variable used to store the address of an
integer value. i.e., j points to an integer.

j itself is a variable and so will have its own unique address associated with it. The value
at j is the address of the variable i. This can be depicted as follows:

Table 9.4 Pointers (Tilak Maharashtra Vidyapeeth, n.d.)

Variable i J
Value 10 3245
Address 3245 4000

Advantage and Disadvantages of using Pointers

Based in the article “Pointers in C programming” by Guru99.com (n.d), these are


the following advantages and disadvantages of using pointers in C.

111
Advantages:

• Pointers are useful for accessing memory locations.


• Pointers provide an efficient way for accessing the elements of an array structure.
• Pointers are used for dynamic memory allocation as well as deallocation.
• Pointers are used to form complex data structures such as linked list, graph, tree,
etc.

Disadvantages:

• Pointers are a little complex to understand.


• Pointers can lead to various errors such as segmentation faults or can access a
memory location which is not required at all.
• If an incorrect value is provided to a pointer, it may cause memory corruption.
• Pointers are also responsible for memory leakage.
• Pointers are comparatively slower than that of the variables.
• Programmers find it very difficult to work with the pointers; therefore, it is
programmer's responsibility to manipulate a pointer carefully.

Lesson 2. Declaration and Initialization of Pointers (Tilak


Maharashtra Vidyapeeth, n.d.)

Based in the article “C Programming” by Tilak Maharashtra Vidyapeeth (n.d),


Declaration of C pointers is similar to the declaration of other variable, but the only
difference in declaration is the use of dereference operator (*).

112
The general form of declaring a pointer variable is as follows:

data type *pointer_name;

In this declaration, the (*) means it is a pointer variable.

• Pointer_name is the name given to the pointer variable and it being a variable
needs space in memory.
• Data type indicates the type of the data to which the pointer variable points.

Example:

int *a;

This declares that the pointer variable points to an integer data type.

char *ch1

This declares that the pointer variable points to a character data type.

float *p

This declares p as a pointer to a floating-point variable.

113
When you declare a pointer variable you have to initialize it by assigning to it the address
of a variable.

int *p. i;

p = &i;

Thus, p is initialized and now contains the address of i. Pointers should not be
used before they are initialized. When the type of a pointer is declared it will hold the
address of that data type only.

Example:

int *i, j;

float p;

i = &p;

The example is invalid since p is declared float and the data type in the pointer declaration
is declared to be of type int.

A pointer variable can also be initialized at the time of declaration also as follows:

float a, *z = &a;

114
Here a is declared to be of type float. Pointer variable z is also declared to hold
address of data type float and hence can hold the address of a. (Note that a has to be
first declared before assigning its address to z i.e., the statement float *z = &a, a; is
invalid. Absolute value cannot be assigned to any pointer variable. Thus, the following is
invalid:

int *p;
p = 100;

Having seen how to declare and initialize pointer variables let us now see how to
make use of the pointer variable to access the value of a variable.

Example: To determine the value of a variable using pointer

main()
{

int i, *ptr, val;


i = 100;
ptr = &i;
val = *ptr;

printf(“\nThe value of i is %d”, i);


printf(“\nThe value of i is %d”, *ptr);
printf(“\nThe value of i is %d”, *&ptr);
printf(“\nThe value of i is %d”, val);
printf(“\nThe address of i is %u”, &i);
printf(“\nThe address of i is %u”, ptr);

Output:

The value of i is 100


The value of i is 100
The value of i is 100
The value of i is 100

115
The address of i is 65496
The address of i is 65496

The program demonstrates the various ways which can be used to determine the
value of a variable. The statement val = *ptr; returns the value of the variable whose
address is stored in ptr to val. Thus *ptr returns the value of the variable i.

ptr = &i;
val = *ptr;

can be combined and written as:

val = *&i;

Remember that val will have the same value as the value of the variable i. Study
thoroughly the concept of pointers before proceeding to the further topics.

I highly recommend to watch this video tutorials by Neso Academy before proceeding to
the next topic:

• Introduction to Pointers in C - https://www.youtube.com/watch?v=f2i0CnUOniA


• Declaring and Initializing Pointers in C -
https://www.youtube.com/watch?v=b3G9RjG4l2s

Lesson 3. Pointers Arithmetic


Based in the article “Understanding C Pointers” by Codewithc.com (2014), Like
other ordinary variables, pointer variables can also be expressed in terms of expression.
The pointer expression is similar to ordinary C expressions to some extent, but in the

116
expression of C pointers, there should be proper use of reference and dereference
operators. Some rules regarding arithmetic for pointers in C are given below:

• A pointer variable can be assigned to the address of an ordinary variable.


• Pointers can be initialized or assigned as NULL; NULL is the symbolic
representation of zero.
• An integer type of variable can be added or subtracted from a pointer variable.
• Pointers in C can’t be divided or subtracted by a constant.
• Two pointer variables can’t be added.
• C pointers cannot be assigned to an ordinary variable.

Pointer variables can be used in expressions (Tilak Maharashtra Vidyapeeth, n.d.)

Example:

float x, p, q, z, *ptr1, *ptr2;


ptr1 = &p;
ptr2 = &q;

Here ptr1 and ptr2 are pointer variables which point to variables of type float. They are
therefore initialized with the addresses of float variables p and q respectively.

Example:

main()
{

float a, b, *p1 = &a, *p2 = &b;


float z;

117
a = 100;
b = 21.8;

printf(“\nThe value of a is %6.2f”, a);


a = *p1 * 10;

printf(“The new value of a is %6.2f”, a);


z = *p1/*p2;

printf(“The value of z is %6.2f”, z);

z = *p1-*p2;

printf(“The new value of z is %6.2f”, z);

Output:

The value of a is 100.00


The new value of a is 1000.00
The value of z is 45.87
The new value of z is 978.20

Note: When using (/) (division operator) in pointer arithmetic remember to have a space
between the (/) and (*) else (/*) will be mistaken as a comment. Thus write *ptr1 / *ptr2
and not *ptr1/*ptr2. With the above example it is clear that with the use of pointers we
have been able to manipulate the values of variables.

Pointers can also be incremented or decremented (Tilak Maharashtra Vidyapeeth, n.d.).

ptr1++

or,

118
ptr2--

are valid in C.

In this case, it is important to understand what happens when pointers are


incremented or decremented. ptr++ will cause the pointer ptr1 to point to the next value
of its type. Thus, if a is an integer and ptr1 is a pointer to a, then when ptr is incremented
its value will be incremented by 2 since an integer is stored in 2 bytes of memory. Thus,
if the pointer ptr1 has an initial value 4820 then ptr++ will cause its value to be 4822 i.e.,
its value is incremented by the length of the data type to which it points. This length is
called the scale factor.

For the purpose of revising, let us once again see the various data types and the number
of bytes they occupy in memory.

Table 8.5 Data Types and Sizes (Tilak Maharashtra Vidyapeeth, n.d.)

Type Size
Int 2 bytes
Char 1 byte
Float 4 bytes
Long int 4 bytes
Double 8 bytes

Example: To demonstrate increment and decrement of pointers

main()
{
int a, *ptr1;
float b, *ptr2;
ptr1 = &a;

119
printf(“\nptr1 is : %u”, ptr1);
ptr1++;
printf(“\nnew ptr1 is %u”, ptr1);

ptr2 = &b;

printf(“\nptr2 is : %u”, ptr2);


ptr2—;
printf(“\nnew ptr2 is %u”, ptr2);

Output:

ptr1 is: 65492


new ptr1 is: 65494

ptr2 is: 65494


new ptr2 is: 65490

In this program ptr1 points to an integer variable whereas ptr2 points to a float
variable. Incrementing ptr1 causes its value to increase by 2 since int occupies 2 bytes
in memory. Decrementing ptr2 causes its value to be decremented by 4 since a float
occupies 4 bytes in memory.

Pointers can be extended as follows (Tilak Maharashtra Vidyapeeth, n.d.):

C also allows us to add integers from pointers.

ptr2 + 4
ptr1+10

120
C also allows to subtract integers from pointers.

ptr1 -10
ptr2 – 2

Example: To add and subtract integers from pointers.

main()
{

int a, b, *ptr1 = &a, *ptr2 = &b; int q = 10, b = 20;

printf(“\nThe value of ptr1 is %d”, ptr1);


*ptr1 = *ptr1 + 10;
printf(“\nThe new value of ptr1 is %d”, *ptr1);

printf(“\nThe value of ptr2 is %d”, *ptr2);


*ptr2 = *ptr2 - 40;
printf(“\nThe new value of ptr2 is %d”, *ptr2);

*ptr2 = ptr2 - ptr1;

printf(“The new value of ptr2 is %d”, *ptr2);

I recommend to check the output of this program and study what happens to the values
of ptr1 and ptr2 when integers are added to and subtracted from them.

Pointers can also be compared as follows (Tilak Maharashtra Vidyapeeth, n.d.):

ptr1 > ptr2


ptr2 < ptr1
ptr1 == ptr2

121
ptr1! = ptr2 and so on. It is however important to note that pointer variables can be
compared provided both variables point to objects of same data type.

Note:

You cannot add two pointers.

ptr1 + ptr2 is Invalid.

You cannot use pointers in Multiplication.

ptr1 * ptr2 is invalid


ptr2 * 10 is invalid

I highly recommend to watch these video tutorials by Neso Academy before proceeding to
the next topic.

• Pointer Arithmetic (Addition) -


https://www.youtube.com/watch?v=FmptkK2XZ0w
• Pointer Arithmetic (Subtraction) -
https://www.youtube.com/watch?v=MgsPbqOKF-c
• Pointer Arithmetic (Increment and Decrement) -
https://www.youtube.com/watch?v=gwqbYnxQGR8
• Pointer Arithmetic (Comparing the Pointers) -
https://www.youtube.com/watch?v=nYHA3eZuhzc

Lesson 4. Pointers and Functions


Having obtained an overview of pointers and learned pointer arithmetic let us now
learn the use of pointers in functions. Based in the article “Understanding C Pointers” by
Codewithc.com (2014), A function can be called either by passing the value of argument
or by passing the address of the arguments. If a function is called by passing the address

122
of the argument, it is known as calling a function by reference. While calling a function by
reference, C pointers are used, and for this the following points should be kept in mind:

• The parameter of a function must be declared as a pointer variable.


• In the function body, dereference operators (*) should be used to withdraw the
values from the memory location or the address.
• While calling a function, argument of the function should be passed as actual
arguments.

We had deferred our discussion of call be reference in functions till we studied pointers.
Let us now see this aspect of functions.

Let us write the program to swap the values of i and j first by using the call by value
method and then study the call by reference method:

Example: Program to exchange the values of i and j.

main()
{

123
int i,j;
i = 10;
j = 50;

printf(“\ni = %d\tj = %d”, i, j);


swap(i,j);
printf(“\ni = %d\t j = %d”, i,j);
}

swap(int a, int b)
{
int z;
z = a;
a = b;
b = z;

printf(“\na = %d\t b = %d”, a, b);


}

Output:

i = 10 j = 50
a = 50 b = 10
i = 10 j = 50

Note: In this function, the values of i and j remain unchanged, only the values of a and
b get interchanged. As we have already studied, the values of the actual arguments merely
get copied into the corresponding formal arguments of the called function. Thus, changes
made to the formal arguments have no effect on the values of the actual arguments. Thus,
even though you manipulate the formal arguments the actual arguments remain
unchanged.

Lesson 4.1 Call by Reference


Based in the article “Understanding C Pointers” by Codewithc.com (2014), In call
by reference we pass not the values but the addresses of the actual arguments to the
formal arguments of the called functions. The formal arguments are declared to be pointer
variables to accept the actual arguments. This implies that with these addresses of the

124
actual arguments we can have access to the actual arguments and be able to manipulate
them. We can thus change the values of the actual variables with this technique. The
following example rewrites the above program by making use of call by reference and thus
actually changing the values of i and j. It illustrates how to pass the addresses as
arguments to the called function.

Example: To swap i and j using call by reference.

void swap(int *, int *)


main()
{

int i,j;
i = 10;
j = 50;

printf(“\ni = %d\tj = %d”, i, j);


swap(&i,&j);
printf(“\ni = %d\t ,j = %d”, i, j);

void swap(int *ptr1, int *ptr2)


{

int k;
k = *ptr1;
*ptr1 = *ptr2;
*ptr2 =k;

Output:

void swap(int *, int *)


main()
{

int i,j;
i = 10;
j = 50;

125
printf(“\ni = %d\tj = %d”, i, j);
swap(&i,&j);
printf(“\ni = %d\t ,j = %d”, i, j);

void swap(int *ptr1, int *ptr2)


{

int k;
k = *ptr1;
*ptr1 = *ptr2;
*ptr2 =k;

Output:

i = 10 j = 50
i = 50 j = 10

Here, the addresses of the variables i and j are copied into the formal arguments *ptr1
and *ptr2 of the called function. With the help of these addresses, we have access to the
actual values of i and j. Thus, the values of i and j are exchanged.

Another example is given below which changes the actual value of a variable. Study it
carefully.

Example: /* Program to demonstrate call by reference */

main()
{

int i;
i = 10;

printf(“\nValue of i is :%d”, i);

126
fn1(&i);

printf(“\nNew value of i is : %d”, i);

void fn1(p)
int *p;
{

*p = *p + 10;

Output:

Value of i is :10
New value of i is :20

In this example, when the function fn1() is called the address of i (and not the value of
i) is passed to fn1(). In the function fn1() the variable ptr is a pointer variable which
points to data type int and so it receives the address of i.

*p =*p +10;

means that 10 gets added to the value which stored at the address p. Hence 10 gets
added to i. This means that call by reference actually allowed you to change the values of
the variables of the calling functions.

We have studied that the return statement can return only one value from the
called function. However, we can make a function return more than one value by making
use of call be reference method. Let us see how this can be done:

Example: To make a function return more than one value.

127
void fn1(int, int, int *, int * );
main()
{

int a, b, sum, prod;

printf(“\nEnter a :”);
scanf(“%d”, &a);
printf(“\nEnter b:”);
scanf(“%d”, &b);

fn1(a,b, &prod, &sum);

printf(“\nThe product of a and b is %d”, prod);


printf(“\nThe sum of a and b is %d”, sum);
}

void fn1(int i, int ,j, int *p, int *s)


{

*p = i*j;
*s = i + j;

Output:

Enter a: 50
Enter b: 10

The product of a and b is: 500


The sum of a and b is: 60

The above example makes efficient use of passing addresses to functions so that
the function returns the sum and product of the numbers a and b. We pass the addresses
of the variables prod and sum as parameters to fn1(). fn1() collects these addresses in
the pointer variables p and s. The values at these variables are then calculated as the
product and sum respectively and are then available in the calling function. Thus, two

128
values are returned to the calling function from the called function.

Example: To make a function return more than one value.

void fn1 (int, float*, float*);


main()
{

int radius;
float circum, area;

printf(“\nEnter radius :”);


scanf(“%d”, &radius);

fn1 (radius, &area, &circum);

printf(“\nArea is : %6.2f”, area);


printf(“\nCircumference is : %6.2f”, circum);

void fn1(int r, float *a, float *c)


{

*a = 3.14*r*r;
*c = 2*3.14*r;

Output:

Enter radius: 7

Area is: 153.86


Circumference is: 43.96

In this example, our function calculates both the area and circumference of the circle. We
are passing the radius and along with it the addresses of the variables area and circum
to the function fn1(). Therefore, area and circum are calculated and their values can be

129
obtained with the help of their addresses.

Lesson 4.2 Pointers to Functions


Based in the article “Understanding C Pointers” by Codewithc.com (2014),
Functions also have an address location in memory. Hence, we can declare a pointer to a
function. A pointer to a function is declared as follows:

type (*fnptr)();

fnptr is a pointer to a function which returns a value of type. The pointer is to be enclosed
in a pair of parentheses.

A function pointer can be used to point to the specific function by assigning the
name of the function to the pointer.

Example:

float (*fnptr)();
float add();
fnptr = add;

It will declare fnptr as a function pointer and initialized it to point to function add. Now
we can use fnptr to call the function add as follow:

*fnptr)(a, b);

Take note that there is a parenthesis around *fnptr. This is as good as calling function
add().

130
add(a ,b)

Lesson 5. Pointers and Arrays (Tilak Maharashtra Vidyapeeth, n.d.)


We have already seen that when we declare an array the elements of the array are
stored in contiguous memory locations. In pointers we have studied that whenever we
increment a pointer it points to the next memory location of its type. Using this, let us now
study pointers and arrays

Based in the article “C Programming” by Tilak Maharashtra Vidyapeeth (n.d), when


an array is declared, the compiler immediately allocates a base address and sufficient
memory to hold all the elements of the array in contiguous memory locations. The base
address is the address of the first element (i.e., 0th index) of the array. The compiler also
defines the array name as a constant pointer to the first element of the array.

Lesson 5.1 Pointers to One-Dimensional Arrays (Tilak


Maharashtra Vidyapeeth, n.d.)

Let us study about pointers and one-dimensional arrays with the help of the
following example: Suppose you declare an array as follows:

int arr[5] = { 10, 20, 30, 40, 50};

Based in the article “C Programming” by Tilak Maharashtra Vidyapeeth (n.d), arr


is an array of type int whose size is five and the elements of the array are initialized in the
declaration. Let us assume that the base address of arr is 2400. Then since each element
of the array is of type int and there are five (5) elements in the array the five elements
will be stored as follows:

131
Figure 9.25 Address of Array Elements (Tilak Maharashtra Vidyapeeth, n.d.)

arr is a constant pointer which points to the first element arr[0]. Thus the address of
arr[0] in our example is 2400.

We can declare an int pointer ptr to point to the array arr as

ptr = arr

or,

ptr = &arr[0];

We already know that when we use the increment operator with the pointer, its
value gets increased by the length of the data type to which it points. Here ptr points to
data type int, therefore incrementing ptr will cause its value to increase by 2 and hence
it will point to the next element of the array which is arr[1]. Thus it is possible to obtain
the addresses of all the elements of arr[] as follows:

ptr = &arr[0] = 2400


ptr + 1 = &arr[1] = 2402
ptr + 2 = &arr[2] = 2404
ptr + 3 = &arr[3] = 2406
ptr + 4 = &arr[4] = 24

Thus, you can obtain the address of the element as: address of nth element = base
address + (n x scale factor of data type) In our case we can determine the address of
the 4th element as:

132
address of the 4th element

= 2400 + (4 x scale factor of int)


= 2400 + (4 x 2)
= 2408

We can use pointers to access the elements of an array. Thus we can access arr[3]
as *(ptr+3), arr[2] as *(ptr + 2) and so on. The pointer accessing method is very fast as
compared to accessing by the index number as arr[2], arr[4] etc. But it depends on the
programmer on how they will access or manipulate the complexity of data structures.

Example: A program to obtain the addresses of all elements in the array.

main()
{

int arr[5] = {10,20, 30, 40, 50};


int i, *ptr;

ptr = &arr[0];

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


{
printf(“Element: %d\tAddress : %u”, *ptr, ptr);
ptr++;
}

Output:

Element: 10 Address: 65488


Element: 20 Address: 65490
Element: 30 Address: 65492
Element: 40 Address: 65494
Element: 50 Address: 65496

133
In the above program note that we have not used indexing to access the elements
of the array. Instead, we have incremented the pointer ptr every time so that it points to
the next memory location of its type. Accessing array elements with pointers is always
faster as compared to accessing them by subscripts. This method can be very effectively
used if the elements are to be accessed in a fixed order according to some definite logic.
If elements are to be accessed randomly, then using subscripts would be easier though
not as fast as accessing them using pointers.

Lesson 5.2 Pointers to Two-Dimensional Arrays (Tilak


Maharashtra Vidyapeeth, n.d.)

Based in the article “C Programming” by Tilak Maharashtra Vidyapeeth (n.d), We


already know that elements of a two-dimensional array are stored row wise. Thus the
base address of a two dimensional array arr[] is the address of the arr[0][0] element
which will be obtained as &arr[0][0]. The compiler then allocates contiguous memory
locations to the array elements row wise i.e., first all the elements of row 1 are stored
then all elements of row 2 and so on. Let us see this representation with the help of the
following example:

int arr[2][5] = {(1,2,3,4,5),(6,7,8,9,10)};

The elements will be stored in memory row wise. If we want to access the element
arr[1][2] we can do it as:

Figure 9.26 Accessing Elements of a 2-D Dimensional Array (Tilak Maharashtra Vidyapeeth,
n.d.)

134
arr[1][2] = *(ptr + 5 x1 +2)
= *(ptr + 7)
= 8

where ptr points to the base address of the array. Thus, to access an element arr[i][j]
the formula would be:

a[i][j] = *(ptr + (no. of cols) x i + j)

Hence it is essential to define the number of columns i.e., size of each row when declaring
a two-dimensional array so that the compiler can determine the storage mapping for the
array elements.

Lesson 5.3 Pointers and Strings (Tilak Maharashtra Vidyapeeth, n.d.)


Based in the article “C Programming” by Tilak Maharashtra Vidyapeeth (n.d), A
string is an array of characters which is terminated by the null character (\0). Thus, the
concept of pointers and one-dimensional arrays can be extended to array of characters.
Let us write a program to determine the values of the elements of the character array with
the help of pointers.

Example: To access elements of a string with pointers.

main()
{

char str1[25] = “Pointers”;


char *cp;

cp = &str1[0];

135
while(*cp != ‘\0’){

printf(“\nCharacter :%c\tAddress : %u”, *cp, cp);


cp++;
}
}

Output:

Character: P Address: 65472


Character: o Address: 65473
Character: i Address: 65474
Character: n Address: 65475
Character: t Address: 65476
Character: e Address: 65477
Character: r Address: 65478
Character: s Address: 65479

Since characters require one byte of storage in memory, incrementing pointer cp will
increment its value by 1 and it will point to the next character in the string.

The concept of single dimension array of characters i.e., string can be extended to
the table of strings. When we declare a two-dimensional array of strings, each string will
be allocated equal length as specified in its declaration. However, in practice the all
strings of the table are rarely equal in length. Hence instead of making each row of a fixed
number of characters we can make each row a pointer to a string of varying lengths.

char *name[3] = {“Jimmy”; “Jill”; “Joseph”};

The above declaration declares name to be an array of three pointers where each pointer
points to the particular name. This can be shown as follows:

136
name[0]----------> Jimmy
name[1]----------> Jill
name[2]----------> Joseph

Had we declared name to be a two dimensional array of strings as name[3][10] it


would have reserved 30 bytes for the array name, where each name would be allocated
10 bytes. But when we declare name to be an array of pointers, where each element points
to a name, the total memory allocated would be 18 bytes as follows:

In order to access the jth character of the ith row: *(name[i] + j) would be useful. Note
that we first select the row, then the jth element of that particular row and then determine
value at address. We can print the names in the array as shown in the following example:

Example:

main()
{

int i;
char *name[3] = {“Jimmy”,“Jill”,“Joseph”};

printf(“\nNames in the array :”);

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


printf(“\n%s”, name[i]);

Assessment Task

Coding Problems: Answer the ff. programs based on the given assessment format.

1. Create a C Program that will take two (2) numbers and perform the following operation
(Addition and Subtraction) using POINTERS.

Sample Output:

137
2. Create a C Program that will take a string from user and count the number of
character(s) using POINTERS.

Sample Output:

3. Create a C Program that will calculate the sum of all elements in an ARRAY using
POINTERS.

Sample Output:

138
Summary

In this module, we studied the new and powerful concept of pointer. Pointers are
particularly important in system programming. Pointers is containing the
addresses of another variable. It is therefore possible to access the value of a variable
either with the help of variable name or with its addresses. Pointers can be used in all
places where arrays are used. We can also invoke functions using pointers.

References

Codewithc.com. (2014). Understanding C Pointers: A Beginner’s Guide.


https://www.codewithc.com/understanding-c-pointers-beginners-guide/

Tilak Maharashtra Vidyapeeth. (n.d.). C Programming.


http://www.freebookcentre.net/programming-books-download/C-Programming-by-Tilak-
Maharashtra-Vidyapeeth.html#

MODULE 10

BASICS OF FILE HANDLING

Introduction

Sometimes, you might have felt that managing different types of files in C gets a
bit complicated, whether it be a text file or a binary file. But this task proves to be quite

139
simple when we talk about file handling in C. File handling in C refers to the task of storing
data in the form of input or output produced by running C programs in data files, namely,
a text file or a binary file for future reference and analysis.

Once we compile and run the program, the output is obtained, but this output is
not stored in the form of information anywhere in the system. What if we want to store
the output produced for future references? After all, most of the software firms write
programs in order to store the output produced as information. This problem can easily
be solved by the implementation of file handling in C. Since most of the computer systems
work with files as it helps in storing information, C offers this benefit of file handling
(Dataflair.com, n.d).

Learning Outcomes

At the end of this module, students should be able to:

• Discuss what is file handling in C and it’s uses.


• Identify the different file types in C.
• Apply the use of basic file handling functions to modify a file.

Lesson 1. File Handling (Dataflair.com, n.d.)


Based in the article “File Handling in C” by Dataflair.com (n.d), A file is nothing but
a source of storing information permanently in the form of a sequence of bytes on a disk.
The contents of a file are not volatile like the C compiler memory. The various operations
available like creating a file, opening a file, reading a file or manipulating data inside a file
is referred to as file handling.

Need for File Handling in C

140
There is a time when the output generated by compiling and running the program
does not serve the purpose. If we want to check the output of the program several times,
it becomes a tedious task to compile and run the same program multiple times. This is
where file handling comes into play. Here are some of the following reasons behind the
popularity of file handling (Dataflair.com, n.d):

• Reusability - It helps in preserving the data or information generated after running


the program.
• Large storage capacity - Using files, you need not worry about the problem of
storing data in bulk.
• Saves time - There are certain programs that require a lot of input from the user.
You can easily access any part of the code with the help of certain commands.
• Portability - You can easily transfer the contents of a file from one computer
system to another without having to worry about the loss of data.

Creating or Opening a File

Based in the article “File Handling Functions in C” by btechsmartclass.com (n.d),


To create a new file or open an existing file, we need to create a file pointer of FILE
type.

Following is the sample code for creating file pointer.

File *f_ptr ;

141
We can use the pre-defined function fopen() to create a new file or to open an
existing file. There are different modes in which a file can be opened.

Consider the following code.

File *f_ptr ;
*f_ptr = fopen("abc.txt", "w") ;

The example above creates a new file called abc.txt if it does not exist otherwise it is
opened in writing mode.

In C programming language, there different modes are available to open a file (We’re going
to talk about the different file modes in later texts).

Lesson 2. Different Files Types in C (Dataflair.com, n.d.)


Based in the article “File Handling in C” by Dataflair.com (n.d), when talking about
files with reference to file handling, we generally refer it to as data files. There are
basically 2 distinct types of data files available in the C programming language:

• Text Files - These are the simplest files a user can create when dealing with file
handling in C. It is created with a .txt extension using any simple text editor.
Generally, we use notepads to create text files. A text file stores information in the
form of ASCII characters internally, but when you open the text file, you would find
the content of the text readable to humans.

Hence, it is safe to say that text files are simple to use and access. But, along with
advantages comes disadvantages as well. Since it is easily readable, it does not
provide any security of information. Moreover, it consumes large storage space.
Hence, there is a different type of file available called binary files which helps us
solve this problem.

142
• Binary Files - A binary file stores information in the form of the binary number
system (0’s and 1’s) and hence occupies less storage space. In simple words, it
stores information in the same way as the information is held in computer memory.
Therefore, it proves to be much easier to access.

It is created with a .bin extension. It overcomes the drawback offered by text files.
Since it is not readable to humans, the information is more secure. Hence, it is safe
to say that binary files prove to be the best way to store information in a data file.

Lesson 3. Opening a Text File in C (Dataflair.com, n.d.)


Based in the article “File Handling in C” by Dataflair.com (n.d), we can use the
fopen() function to create or open a file. It is pretty obvious that creating or opening a file
is the first step in file handling. Once the file has been created, it can be opened, modified
or deleted.

Syntax Opening a File

*fpointer = FILE *fopen(const char *file_name, const char *mode);

• fpointer is the pointer to the file that establishes a connection between the file
and the program.
• file_name is the name of the file.
• mode is the mode in which we want to open our file.

These are the following modes that you can use in a file:

Table 10.6 File Modes (Codewithc.com, 2014)

Mode Description
r We use it to open a text file in reading mode
w We use it to open or create a text file in writing mode.
a We use it to open a text file in append mode.

143
r+ We use it to open a text file in both reading and writing mode.
w+ We use it to open a text file in both reading and writing mode.
a+ We use it to open a text file in both reading and writing mode.
rb We use it to open a binary file in reading mode.
wb We use it to open or create a binary file in writing mode.
ab We use it to open a binary file in append mode.
rb+ We use it to open a binary file in both reading and writing mode.
wb+ We use it to open a binary file in both reading and writing mode.
ab+ We use it to open a binary file in both reading and writing mode.

Lesson 4. Closing a Text File in C (Dataflair.com, n.d.)


Based in the article “File Handling in C” by Dataflair.com (n.d), we can use the
fclose() function to close a file that is already open. It is pretty obvious that the file needs
to be opened so that the operation to close a file can be performed.

Syntax Opening a File

int fclose(FILE *fpointer);

Here, the fpointer is the pointer associated with closing the file. This function is
responsible for returning the value 0 if the file is closed successfully. Otherwise, EOF (end
of file) in case of any error while closing the file.

Lesson 5. Reading and Writing a Text File in C (Dataflair.com,


n.d.)

After discussing how to open and close a file, it is important to note that there are
3 types of streams (sequence of bytes) in a file (Dataflair.com, n.d):

• Input
• Output
• Input / Output

144
The simplest functions used while performing operations on reading and writing
characters in a file are getc() and putc() respectively.

• getc() – it is used to read characters from a line.


• putc() – it is used to write characters in a file.

In order to read and write a set of data in a file, we use the fscanf() and fprintf()
operators.

• fscanf() it is used to read a set of data from a file.


• fprintf() it is used to write a set of data from a file.

Example: Program that illustrates the use of fprintf() to write a text file.

int main()
{

char character;
FILE *fpointer;

fpointer = fopen("C:\\program.txt","w");

if(fpointer == NULL)
{
printf("Error! The file does not exist.");
}

printf("Enter a character: ");


scanf("%c",&character);

fprintf(fpointer,"%c",character);
fclose(fpointer);
}

After successfully compiling the above code, a text file would be generated in your system
drive. When we open the text file, it would display the character entered in the program.
Try running the program in your device and study the process.

145
After developing an understanding of how to write in a file, let us proceed with how to
read a line (Dataflair.com, n.d.).

Example: Program that illustrates the use of fscanf() to read a text file.

int main()
{
char character;
FILE *fpointer;

if ((fpointer = fopen("C:\\program.txt","r")) == NULL)


{
printf("Error! The file does not exist.");
exit(0);
}

fscanf(fpointer,"%c", &character);
printf("The character is: %c", character);
fclose(fpointer);

return 0;
}

Try running the program in your system and study how it works.

Now, let us try to understand the difference between the write mode and append mode.

Although they have seemingly similar functions, there are some differences between the
two. The write mode is denoted by “w” whereas the append mode is denoted by “a”.
Using the write mode, you may lose data. When you run your program for the second
time, the system overwrites the new output produced by the program if the user gives a
different input than the one given in the previous program. In contrast to this situation,
the append mode simply adds more data to the existing data. Therefore, from this
discussion, it is evident that the append mode is better than the write mode
(Dataflair.com, n.d).

146
After understanding some of the basic operations in text files, let us carry on our
discussion forward on binary files. We can open and close the binary file in a similar
fashion like text files. The difference arises while reading and writing in a binary file.

Lesson 6. Reading and Writing a Binary File in C (Dataflair.com,


n.d.)

Based in the article “File Handling in C” by Dataflair.com (n.d), we can use the
fread() and fwrite() function to read and write data from a binary file respectively.

• fread() it is used to read binary data.


• fwrite() it is used to write binary data.

Working with binary files is a bit more complicated than working with text files as the
syntax involves the use of more arguments. The function fread() and fwrite() both take
four (4) arguments to work.

fread() Syntax:

fread(data_address, data_size, number_of_data_items, file_pointer);

fwrite() Syntax:

fwrite(data_address, data_size, number_of_data_items,file_pointer);

Example: Program that illustrates how to read a binary file in C.

struct example
{
int x;
};

int main()

147
{

int i;
FILE *pointer;
struct example e;
e.x = 10;
pointer = fopen("example.bin","rb");

if(!pointer)
{
printf("Error! The file does not exist.");
exit(0);
}

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


{
fread(&e, sizeof(struct example),1 , pointer);
printf("%d\n",e.x);
}

fclose(pointer);
return 0;

Output:

10
10
10
10
10

Try running the program in your system and study how it works.

In a similar fashion, you can write content in a binary file using the fwrite() function.

Example: Program that illustrates how to write a binary file in C.

int main()
{

char line[1000];

148
FILE *fpointer;
fpointer = fopen("char.txt", "w");

if(fpointer == NULL)
{
printf("Error!");
exit(0);
}

printf("Enter a statement: ");


fgets(line,1000,stdin);

fprintf(fpointer,"%s", line);
fclose(fpointer);

return 0;
}

Try running the program in your system and study how it works.

I highly recommend to watch these video tutorials by Learning Lad about File Handling
before proceeding to the assessment tasks.

• File Handling in C -
https://www.youtube.com/watch?v=wVDfRzBp8iE&list=PLfVsf4Bjg79BOmLYBR
TwqCIkGPiOWb7xj&index=1

Assessment Task

Coding Problems: Answer the ff. programs based on the given assessment
format.

1. Create a C Program that will create, store and display the following
information in a text file.

Filename: personal_info_txt

Personal Information:

149
Name:
Age:
Birthdate:
Course & Section:
Address:

Sample Output:
Name: John Ren G. Santos
Age: 24
Birthdate: August 15, 1996
Course: Bachelor of Science in Information Technology
Address: Pila Laguna

2. Create a C Program that will count the number of words in the text file
created in the question #1.

Summary

In this module, we discussed an important concept in the C, that is, file handling.
A file is a permanent place on a disk where related data is stored. C provides number of
functions for opening a file, reading data from a file, writing to a file, closing a file. We
understood the basic meaning of file handling, why is it used and what are the 2 types of
data files available in C. Further, we even discussed the various operations associated
with both the types of data files with the help of illustrative programs.

150
References

btechsmartclass.com. (n.d.). File Handling Functions in C.


http://www.btechsmartclass.com/c_programming/C-File-Handling-Functions.html

Codewithc.com. (2014). Understanding C Pointers: A Beginner’s Guide.


https://www.codewithc.com/understanding-c-pointers-beginners-guide/

Dataflair.com. (n.d.). File Handling in C – An Easy Concept to Manage your Files in C.


https://data-flair.training/blogs/file-handling-in-c/

Guru99.com. (n.d.). Pointers in C Programming: What is Pointer, Types & Examples.


https://www.guru99.com/c-pointers.html#:~:text=Advantages of Pointers in C Pointers are
useful,for dynamic memory allocation as well as deallocation.

Tilak Maharashtra Vidyapeeth. (n.d.). C Programming.


http://www.freebookcentre.net/programming-books-download/C-Programming-by-Tilak-
Maharashtra-Vidyapeeth.html#

MODULE 11

FILE HANDLING FUNCTIONS

Introduction

Sometimes, you might have felt that managing different types of files in C gets a
bit complicated, whether it be a text file or a binary file. But this task proves to be quite
simple when we talk about file handling in C. File handling in C refers to the task of storing

151
data in the form of input or output produced by running C programs in data files, namely,
a text file or a binary file for future reference and analysis.

Once we compile and run the program, the output is obtained, but this output is
not stored in the form of information anywhere in the system. What if we want to store
the output produced for future references? After all, most of the software firms write
programs in order to store the output produced as information. This problem can easily
be solved by the implementation of file handling in C. Since most of the computer systems
work with files as it helps in storing information, C offers this benefit of file handling
(Dataflair.com, n.d).

Learning Outcomes

At the end of this module, students should be able to:

• Identify the different functions used in File Handling.


• Apply the usage of reading, writing, closing and cursor positioning functions to
perform flexible modification in a file.

Lesson 1. Reading from a File (btechsmartclass.com, n.d.)


Based in the article “File Handling Functions in C” by btechsmartclass.com (n.d),
the reading from a file operation is performed using the following pre-defined file handling
methods.

1. getc() - this function is used to read a character from specified file which is opened
in reading mode. It reads from the current position of the cursor. After reading the
character the cursor will be at next character.

Example:

152
int main(){

FILE *fp;
char ch;

fp = fopen("MySample.txt","r");
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);

getch();
return 0;
}

2. getw() - this function is used to read an integer value form the specified file which
is opened in reading mode. If the data in file is set of characters then it reads ASCII
values of those characters.

Example:

int main(){

FILE *fp;
int i,j;

fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);

fp = fopen("MySample.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j); //
65 + 97 = 162

fclose(fp);
getch();

return 0;
}

153
3. fscanf() - This function is used to read multiple datatype values from specified file
which is opened in reading mode.

Example:

int main(){

char str1[10], str2[10], str3[10];


int year;
FILE * fp;

fp = fopen ("file.txt", "w+");


fputs("We are in 2016", fp);
rewind(fp);

fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);


printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );

fclose(fp);
getch();
return 0;
}

4. fgets() - this function is used for reading a set of characters from a file which is
opened in reading mode starting from the current cursor position. The fgets()
function reading terminates with reading NULL character.

Example:

int main(){

FILE *fp;
char *str;

fp = fopen ("file.txt", "r");


fgets(str,6,fp);

printf("str = %s", str);


fclose(fp);

154
getch();

return 0;
}

5. fread() - this function is used to read specific number of sequence of characters


from the specified file which is opened in reading mode.

Example:

int main(){

FILE *fp;
char *str;

fp = fopen ("file.txt", "r");


fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0;

printf("str = %s", str);

fclose(fp);
getch();

return 0;
}

Lesson 2. Writing into a File (btechsmartclass.com, n.d.)


Based in the article “File Handling Functions in C” by btechsmartclass.com (n.d),
The writing into a file operation is performed using the following pre-defined file handling
functions.

1. putc() - this function is used to write/insert a character to the specified file when
the file is opened in writing mode.

Example:

int main(){

FILE *fp;

155
char ch;

fp = fopen("C:/TC/EXAMPLES/MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();
return 0;
}

2. putw() - this function is used to writes/inserts an integer value to the specified


file when the file is opened in writing mode.

Example:

int main(){

FILE *fp;
int i;

fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();

return 0;
}

3. fprintf() - this function is used to writes/inserts multiple lines of text with mixed
data types (char, int, float, double) into specified file which is opened in writing
mode.

Example:

int main(){

FILE *fp;
char *text = "\nthis is example text";
int i = 10;

fp = fopen("MySample.txt","w");

156
fprintf(fp,"This is line1\nThis is line2\n%d", i);

fprintf(fp,text);

fclose(fp);
getch();

return 0;
}

4. fputs() - this function is used to insert string data into specified file which is
opened in writing mode.

Example:

int main(){

FILE *fp;
char *text = "\nthis is example text";

fp = fopen("MySample.txt","w");
fputs("Hi!\nHow are you?",fp);

fclose(fp);
getch();

return 0;
}

5. fwrite() - this function is used to insert specified number of characters into a


binary file which is opened in writing mode.

Example:

int main(){

FILE *fp;
char *text = "Welcome to C Language";

fp = fopen("MySample.txt","wb");
fwrite(text,sizeof(char),5,fp);

fclose(fp);
getch();

157
return 0;
}

Lesson 3. Closing a File (btechsmartclass.com, n.d.)


Based in the article “File Handling Functions in C” by btechsmartclass.com (n.d),
Closing a file is performed using a pre-defined function fclose().

fclose( *f_ptr )

The function fclose() returns '0' on success of file close otherwise it returns EOF (End Of
File).

Lesson 4. Cursor Positioning Functions in Files


(btechsmartclass.com, n.d.)

Based in the article “File Handling Functions in C” by btechsmartclass.com (n.d),


C programming language provides various pre-defined methods to set the cursor position
in files. The following are the methods available in C, to position cursor in a file.

1. ftell() - this function returns the current position of the cursor in the file.

Example:

158
int main(){

FILE *fp;
int position;

fp = fopen ("file.txt", "r");


position = ftell(fp);

printf("Cursor position = %d\n",position);


fseek(fp,5,0);
position = ftell(fp);

printf("Cursor position = %d", position);


fclose(fp);

getch();

return 0;
}

2. rewind() - this function is used reset the cursor position to the beginning of the
file.

Example:

int main(){

FILE *fp;
int position;

fp = fopen ("file.txt", "r");


position = ftell(fp);

printf("Cursor position = %d\n",position);


fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);

printf("Cursor position = %d", position);

fclose(fp);
getch();

return 0;

159
}

3. fseek() - this function is used to set the cursor position to the specific position.
Using this function, we can set the cursor position from three different position
they are as follows.
o from beginning of the file (indicated with 0)
o from current cursor position (indicated with 1)
o from ending of the file (indicated with 2)

Example:

int main(){

FILE *fp;
int position;

fp = fopen ("file.txt", "r");


position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);

fclose(fp);
getch();
return 0;
}

Assessment Task

Coding Problems: Answer the ff. programs based on the given assessment
format.

1. Create a C Program that will create, store and display the following
information in a binary file.

Filename: personal_info_bin

160
Personal Information:
Name:
Age:
Birthdate:
Course & Section:
Address:

Sample Output:
Name: John Ren G. Santos
Age: 24
Birthdate: August 15, 1996
Course: Bachelor of Science in Information Technology
Address: Pila Laguna

2. Create a C Program that will insert the following information at the first
line of the “personal_info_bin” file.

Information:
Student ID: 151-1237
Academic Year: 2nd Semester 2021

Summary

In this module, you can categorize the file handling functions by their uses in terms
of reading, writing, closing and cursor positioning in a file. In reading from a file, you can
use the getc(), getw(), fscanf(), fgets() and fread() functions. In writing into a file, you can
use the putc(), putw(), fprintf(), fputs() and fwrite() functions. In closing a file, you can
use the fclose() function. In positioning the cursor in a file, you can use the ftell(), rewind()
and fseek() functions.

161
References

btechsmartclass.com. (n.d.). File Handling Functions in C.


http://www.btechsmartclass.com/c_programming/C-File-Handling-Functions.html

Codewithc.com. (2014). Understanding C Pointers: A Beginner’s Guide.


https://www.codewithc.com/understanding-c-pointers-beginners-guide/

162
Dataflair.com. (n.d.). File Handling in C – An Easy Concept to Manage your Files in C.
https://data-flair.training/blogs/file-handling-in-c/

Guru99.com. (n.d.). Pointers in C Programming: What is Pointer, Types & Examples.


https://www.guru99.com/c-pointers.html#:~:text=Advantages of Pointers in C Pointers are
useful,for dynamic memory allocation as well as deallocation.

Tilak Maharashtra Vidyapeeth. (n.d.). C Programming.


http://www.freebookcentre.net/programming-books-download/C-Programming-by-Tilak-
Maharashtra-Vidyapeeth.html#

163

You might also like