CC 1202 Computer Programming 2 Final
CC 1202 Computer Programming 2 Final
(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
ii
List of Tables
Table Description
iii
List of Figures
Figure Description
iv
MODULE 9
POINTERS
Introduction
Learning Outcomes
• 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.
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.
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:
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.
Example:
main()
{
109
int a;
char ch1;
float b;
a = 100;
ch1 = ‘Z’;
b = 40.85;
Output:
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.
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:
Variable i J
Value 10 3245
Address 3245 4000
111
Advantages:
Disadvantages:
112
The general form of declaring a pointer variable is as follows:
• 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
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.
main()
{
Output:
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;
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:
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:
Example:
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()
{
117
a = 100;
b = 21.8;
z = *p1-*p2;
Output:
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.
ptr1++
or,
118
ptr2--
are valid in C.
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
main()
{
int a, *ptr1;
float b, *ptr2;
ptr1 = &a;
119
printf(“\nptr1 is : %u”, ptr1);
ptr1++;
printf(“\nnew ptr1 is %u”, ptr1);
ptr2 = &b;
Output:
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.
ptr2 + 4
ptr1+10
120
C also allows to subtract integers from pointers.
ptr1 -10
ptr2 – 2
main()
{
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.
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:
I highly recommend to watch these video tutorials by Neso Academy before proceeding to
the next topic.
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:
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:
main()
{
123
int i,j;
i = 10;
j = 50;
swap(int a, int b)
{
int z;
z = a;
a = b;
b = z;
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.
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.
int i,j;
i = 10;
j = 50;
int k;
k = *ptr1;
*ptr1 = *ptr2;
*ptr2 =k;
Output:
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);
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.
main()
{
int i;
i = 10;
126
fn1(&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:
127
void fn1(int, int, int *, int * );
main()
{
printf(“\nEnter a :”);
scanf(“%d”, &a);
printf(“\nEnter b:”);
scanf(“%d”, &b);
*p = i*j;
*s = i + j;
Output:
Enter a: 50
Enter b: 10
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.
int radius;
float circum, area;
*a = 3.14*r*r;
*c = 2*3.14*r;
Output:
Enter radius: 7
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.
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)
Let us study about pointers and one-dimensional arrays with the help of the
following example: Suppose you declare an array 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.
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:
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
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.
main()
{
ptr = &arr[0];
Output:
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.
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:
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.
main()
{
cp = &str1[0];
135
while(*cp != ‘\0’){
Output:
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.
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
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”};
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
MODULE 10
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
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):
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.
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).
• 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.
• 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:
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.
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.
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.
In order to read and write a set of data in a file, we use the fscanf() and fprintf()
operators.
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.");
}
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;
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.
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.
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:
fwrite() Syntax:
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);
}
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.
int main()
{
char line[1000];
148
FILE *fpointer;
fpointer = fopen("char.txt", "w");
if(fpointer == NULL)
{
printf("Error!");
exit(0);
}
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
MODULE 11
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
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(){
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;
154
getch();
return 0;
}
Example:
int main(){
FILE *fp;
char *str;
fclose(fp);
getch();
return 0;
}
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;
}
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;
}
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;
}
fclose( *f_ptr )
The function fclose() returns '0' on success of file close otherwise it returns EOF (End Of
File).
1. ftell() - this function returns the current position of the cursor in the file.
Example:
158
int main(){
FILE *fp;
int position;
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;
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;
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
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/
163