PPS Unit-V Full Notes
PPS Unit-V Full Notes
Unit-V
UNIT – V
File Handling: I/O streams, File operations, file modes, Sequential, Random
accessing of files, Command line arguments
Searching and Sorting Techniques: Searching-Linear search and Binary
search, Sorting- Bubble sort and Selection sort
FILE
When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter
them all.However, if you have a file containing all the data, you can easily
access the contents of the file using few commands in C.
You can easily move your data from one computer to another without any
changes.
File I/O:-
Sometimes it is necessary to store the data in a manner that can be later retrieved and
displayedeither in a part or in whole. This medium is usually a “file” on the disk.
a) Formatted functions:- The file input function fscanf( ) and the file output function
fprintf( )are called formatted file I/O functions.
b)Unformatted functions:- The input functions like getc( ), getw( ), and fread( ) are
called unformatted file input functions and putc( ), putw( ), and fwrite( ) functions are
unformatted file output functions. Each and every function is having its own syntax
and meaning.
File streams:- Stream is either reading or writing of data. The streams are designed to
allow the user to access the files efficiently. A stream is a file or physical device like
key board, printer,monitor, etc., The FILE object uses these devices. When a C
program is started, the operating system is responsible for opening three streams:
standard input stream (stdin), standard output stream (stdout), standard
error(stderr).Normally the stdin is connected to the keyboard, the stdout and stderr
are connected to the monitor.
Files
File is a collection of bytes that is stored on secondary storage devices like Hard disk.
OR
Programming for Problem Solving using C
Unit-V
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.
Note: All files related function are available in stdio.h header file.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better
security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
When working with files, you need to declare a pointer of type file. This declaration is
needed
Syntax
FILE *fp;
The fopen() function is used to create a new file or to open an existing file.
General Syntax :
fp = fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Closing a File
The file (both text and binary) should be closed after reading/writing.
File name is a group of characters that make up a valid file name for the
operating system. It may contain two parts, a primary name and an optional period
with the extension.
Examples: abc.dat
Programming for Problem Solving using C
Unit-V
Xyz.txt
Prog.c
Stu.cpp
1) Data structure of a file is defined as FILE in the library of standard I/O function
definitions. Therefore, all files should be declared as type FILE before they are used.
FILE is a defined data type.
When we open a file, we must specify what we want to do with the file. For
example we may write data to the file or read the data from already existing file.
The above statement declares the variable fptr as a “pointer to the data type FILE”.
Fptr=fopen(―filename‖,‖mode‖);
fopen() opens the named file name and assigns an identifier to the FILE type pointer
fptr. This pointer, which contains all the information about the file, is subsequently
used as a communication link between the system and the program.
This statement also specifies the purpose of opening this file. The mode does
this job.
Note that both the filename and mode are specified as strings. They should be
enclosed in double quotation marks. Consider the following statements:
Ex.
FILE *p1,*p2;
3) Using the C statements process the data for which purpose the file is opened.
A file must be closed as soon as all operations on it have been completed. This
ensures that all outstanding information associated with the file is flushed out from
the buffers and all links to the file are broken. It also prevents any accidental misuse
of the file. In case, there is a limit to the number of files that can be kept open
simultaneously, closing of unwanted files might help open the required files. Another
instance where we have to close a file is when we want to reopen the same file in a
different mode. The I/O library supports a function to do this for us . It takes the
following form
fclose(file_ptr);
This would close the file associated with the FILE pointer file-pointer.
Ex: fclose(p1);
As a matter of fact all file are closed automatically whenever a program terminates.
However, closing a file as soon as you are done with it is a good programming habit.
C imposes no structure for a file. Thus, notaions like a record of a file do not
exist as part of the C language. Therefore, the programmer must provide any file
structure to meet the requirement of each particular application.
The following program creates a simple sequential –access file that might be
used in an accounts receivable system to help keep track of the amounts owed by a
company’s credit clients.
#include<stdio.h>
#include<conio.h>
void main()
int account;
char name[30];
double balance;
Programming for Problem Solving using C
Unit-V
FILE *cfptr;/* cfptr=clients.dat file pointer*/
if((cfptr=fopen("clients.dat","w"))==NULL)
else
scanf("%d%s%lf",&account,name,&balance);
while(!feof(stdin))
fprintf(cfptr,"%d%s%.2f",account,name,balance);
scanf("%d%s%lf",&account,name,&balance);
fclose(cfptr);
OUTPUT: Enter the account, name and balance ( (ctrl+z) to stop input)
Mode Description
r opens a text file in read mode
w opens a text file in write mode
Programming for Problem Solving using C
Unit-V
a opens a text file in append mode
r+ opens a text file in read and write
mode
w+ opens a text file in read and write
mode
a+ opens a text file in read and write
mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both
are used to write in a file. In both the modes, new file is created if it doesn't exists
already.
The only difference they have is, when you open a file in the write mode, the file is
reset, resulting in deletion of any data already present in the file. While in append
mode this will nothappen. Append mode is used to append or add data to the existing
data of file(if any). Hence,when you open a file in Append(a) mode, the cursor is
positioned at the end of the present data in the file.
File accessing method are two types 1) Sequential 2) Random access files.
1. Sequential Access — The data are placed in the file in a sequence like
beads on a string. Data are processed in sequence, one after another. To
reach a particular item of data, all the data that proceeds it first must be
read.
2. Random Access — The data are placed into the file by going directly to the
location in the file assigned to each data item. Data are processed in any
order. A particular item of data can be reached by going directly to it,
without looking at any other data.
Syntax of fprintf is
Programming for Problem Solving using C
Unit-V
fprintf (fp, “control string”, list);
Note:
Note:
EOF – End of file (when EOF encountered the reading / writing should be terminated)
Example:
#include <stdio.h>
main(){
FILE *fp;
fclose(fp);//closing file
#include <stdio.h>
int main()
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
Programming for Problem Solving using C
Unit-V
{
printf("Error!");
exit(1);
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
#include <stdio.h>
int main()
int num;
FILE *fptr;
exit(1);
fscanf(fptr,"%d", &num);
fclose(fptr);
return 0;
}
Programming for Problem Solving using C
Unit-V
Input/Output Operation on files
fputc() function
putc ( ):-Putting a character in to the file. It works with only character data
type. One character at a time can write into a file.
Example:
#include <stdio.h>
main(){
FILE *fp;
fclose(fp);//closing file
Programming for Problem Solving using C
Unit-V
}
file1.txt
fgetc() function
The fgetc() function returns/read a single character from the file. It gets a character
from the
getc ( ): getting a character from the file, or reading the file information
character by character at a time, upto the end of the file by using this function.
ch = getc (fp);
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
fclose(fp);
getch();
Output:
myfile.txt
Programming for Problem Solving using C
Unit-V
this is simple text message
fputs()
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
Output:
myfile2.txt
hello c programming
fgets()
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char text[300];
Programming for Problem Solving using C
Unit-V
clrscr();
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
getch();
Output:
hello c programming
These are integer oriented functions. These are similar to above functions and are
used to readand write integer values. These are useful when we deal with only integer
data. The general format is
Ex: int x = 5;
putw(x,fp);
Ex: int x;
x = getw (fp);
1.fseek()
The fseek() function is used to set the file pointer to the specified offset. It is used to
write datainto file at desired location.
The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location where
the offset starts.Different Whence in fseek
Programming for Problem Solving using C
Unit-V
Whence Meaning
SEKK_CUR Starts the offset from the current location of the cursor in the file.
or
0 beginning of file
1 current position
2 end of file
Eg: fseek (fp, 0L,0); - go to the beginning of the file. (Similar to rewind).
fseek (fp, 0L,2); -go to the end of the file, past the last character of the file.
Example:
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fclose(fp);
}
Programming for Problem Solving using C
Unit-V
myfile.txt
2.rewind()
This function places the file pointer to the beginning of the file, irrespective of where it
is present right now. It takes file pointer as an argument.
Syntax:
rewind( fp);
Example:
File: file.txt
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
while((c=fgetc(fp))!=EOF){
printf("%c",c);
fclose(fp);
Programming for Problem Solving using C
Unit-V
getch();
} Output:
As you can see, rewind() function moves the file pointer at beginning of the file that is
why "this is simple text" is printed 2 times. If you don't call rewind() function, "this is
simple text" will be printed only once.
3.ftell()
The ftell() function returns the current file position of the specified stream. We can use
ftell()
function to get the total size of a file after moving file pointer at the end of file. We can
use
syntax:
n = ftell(fp);
Example:
#include <stdio.h>
#include <conio.h>
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
getch();
Programming for Problem Solving using C
Unit-V
}
Output:
So far we have seen how to input values in C code during compile-time and runtime.
To do that, we declared variables in the main() and then worked on them but there is a
way to input values without declaring it in the main().
C offers us a feature called "command line argument" using which we can enter
values from the command line at the time of execution. Command line argument is a
parameter supplied to the program when it is invoked or run.
They are used when we need to control our program from outside instead of
hard-coding it.
They make installation of programs easier.
Syntax:
Here, argc counts the number of arguments on the command line and argv[ ] is
a pointer array which holds pointers of type char which points to the arguments
passed to the program.
Let's see a simple code example to check whether any command line arguments is
provided to the code or not..
#include<stdio.h>
if(argc < 2)
From the above example, we can infer that the first command line argument
is the program file name, which is always added by default by the compiler.
#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
Compile the above code using command: gcc name_of_file.c, then run it
using: ./a.out Welcome to Studytonight, we have provided command line argument
while running the compiled code.
1 : Welcome
2 : to
3 : Studytonight
Programming for Problem Solving using C
Unit-V
We provided 3 words seperated by space as arguments, while running the code.
So, they will be considered as three separate arguments.
Let's see how inclusion of quotes changes the output of the same program.
1 : welcome to studytonight
Here, we have provided all the 3 words enclosed in a double quote. So, it is
considered as a single argument. Same thing happens with single quotes.
1 : welcome to studytonight
Similarly, we can give int and float type arguments but they will be treated
as strings.
1:1
2:0
3:a
4 : 5.07
Programming for Problem Solving using C
Unit-V
Searching is an operation or a technique that helps finds the place of a given element
or value in the list. Any search is said to be successful or unsuccessful depending
upon whether the element that is being searched is found or not. Some of the
standard searching technique that is being followed in data structure is listed below:
1. Linear Search
2. Binary Search
LINEAR SEARCH
Linear search is a very basic and simple search algorithm. In Linear search, we search
an element or value in a given array by traversing the array from the starting, till the
desired elementor value is found.
It compares the element to be searched with all the elements present in the array and
when the element is matched successfully, it returns the index of the element in the
array, else it return -1.
Linear Search is applied on unsorted or unordered lists, when there are fewer
elements in a list.
For Example,
Linear Search
33
Linear Search
Linear search is a sequential searching algorithm where we start from one end and check every
element of the list until the desired element is found. It is the simplest searching algorithm.
Programming for Problem Solving using C
Unit-V
How Linear Search Works?
The following steps are followed to search for an element k = 1 in the list below.
1. Start from the first element, compare k with each element x . Compare with each element
.
Element found
Programming for Problem Solving using C
Unit-V
3. Else, return not found .
Algorithm
Step 1: Set i to 1
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 8: Exit
Pseudocode
end if
end for
end procedure
2. It has a time complexity of O(n), which means the time is linearly dependent on the
Programming for Problem Solving using C
Unit-V
number of elements, which is not bad, but not that good too.
BINARY SEARCH
Binary Search is used with sorted array or list. In binary search, we follow the
following
steps:
1. We start by comparing the element to be searched with the element in the middle of
the list/array.
then we pick the elements on the right side of the middle element(as the list/array is
sorted, hence on the right, we will have all the numbers greater than the middle
step 1.
Binary Search is useful when there are large number of elements in an array and they
are sorted. So a necessary condition for Binary search to work is that the list/array
should be sorted.
2. It has a time complexity of O(log n) which is a very good time complexity. It has a
simple implementation.
Programming for Problem Solving using C
Unit-V
Binary search is a fast search algorithm with run-time complexity of Ï(log n). This
search algorithm works on the principle of divide and conquers. For this algorithm to
work properly, the data collection should be in the sorted form.
Binary search looksfor a particular item by comparing the middle most item of the
collection.If a match occurs, then the index of item is returned. If the middle item is
greater than the item,then the item is searched in the sub-array to the left of the
middle item. Otherwise, the item issearched for in the sub-array to the right of the
middle item. This process continues on the subarray as well until the size of the sub
array reduces to zero.
For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example. The following is our sorted
array and let us assume that we need to search the location of value 31 using binary
search.
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
Now we compare the value stored at location 4, with the value being searched, i.e. 31.
We
find that the value at location 4 is 27, which is not a match. As the value is greater
than 27 and we
have a sorted array,so we also know that the target value must be in the upper portion
of the array.
Programming for Problem Solving using C
Unit-V
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
A ! sorted array
n ! size of array
x ! value to be searched
Set lowerBound = 1
Set upperBound = n
Our new mid is 7 now. We compare the value stored at location 7 with our target value
31.
The value stored at location 7 is not a match, rather it is more than what we are
looking for. So, the value must be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a
match.
Binary search halves the searchable items and thus reduces the count of comparisons
to bemade to very less numbers.
Pseudocode
Procedure binary_search
A ! sorted array
n ! size of array
x ! value to be searched
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
if A[midPoint] = x
end while
end procedure
SORTING
Preliminaries
A sorting algorithm is an algorithm that puts elements of a list in a certain order. The
most used orders are numerical order and lexicographical order. Efficient sorting is
important to optimizing the use of other algorithms that require sorted lists to work
correctly and for producing human - readable input.
* Computational complexity (worst, average and best case) in terms of the size of the
list (N).For typical sorting algorithms good behaviour is O(NlogN) and worst case
behavior is O(N2) and the average case behaviour is O(N).
* Memory Utilization
* No. of comparisions.
* Methods applied like Insertion, exchange, selection, merging etc. Sorting is a process
of linear ordering of list of objects.
Internal Sorting
External Sorting
if A[midPoint] < x
eg : - Bubble sort, Insertion sort, Shell sort, Quick sort, Heap sort, etc.
External Sorting, takes place in the secondary memory of a computer, Since the
number of objects to be sorted is too large to fit in main memory.
The bubble sort makes multiple passes through a list. It compares adjacent items and
exchanges those that are out of order. Each pass through the list places the next
largest value in its proper place. In essence, each item “bubbles” up to the location
where it belongs.
Fig. 5.1 shows the first pass of a bubble sort. The shaded items are being compared to
see if they are out of order. If there are n items in the list, then there are n - 1n - 1
pairs of items that need to be compared on the first pass. It is important to note that
once the largest value in the list is part of a pair, it will continually be moved along
until the pass is complete.
2. If the first element is greater than the second element, they are swapped.
3. Now, compare the second and the third elements. Swap them if they are not in order.
2. Remaining Iteration
In each iteration, the comparison takes place up to the last unsorted element.
Programming for Problem Solving using C
Unit-V
The array is sorted when all the unsorted elements are placed at their correct positions.
#include<stdio.h>
bubblesort(int a[],int n)
{
int temp,p,c;
for(p=1;p<=n-1;p++)
{
for(c=1;c<=n-p;c++)
{
if(a[c]>a[c+1])
{
temp=a[c];
Programming for Problem Solving using C
Unit-V
a[c]=a[c+1];
a[c+1]=temp;
}
}
}
}
int main()
{
int a[5],n,i;
printf("enter n value");
scanf("%d",&n);
printf("enter %d elements into array",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
bubblesort(a,n);
printf("after sauting elements are");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
return 1;
}
Output:
order (Ascending or Descending). In selection sort, the first element in the list
is selected and it is compared repeatedly with all the remaining elements in the
list. If any element is smaller than the selected element (for Ascending order),
Programming for Problem Solving using C
Unit-V
then both are swapped so that first position is filled with the smallest element
in the sorted order. Next, we select the element at a second position in the list
and it is compared with all the remaining elements in the list. If any element is
smaller than the selected element, then both are swapped. This procedure is
repeated until the entire list is sorted.
Step 1 - Select the first element of the list (i.e., Element at first position
in the list).
Step 2: Compare the selected element with all the other elements in the
list.
Step 4: Repeat the same procedure with element in the next position in
the list till the entire list is sorted.
Example:
For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is stored presently, we search the whole list and
find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the
minimum value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the
list in a linear manner.
We find that 14 is the second lowest value in the list and it should appear at
the second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted
manner.
Programming for Problem Solving using C
Unit-V
The same process is applied to the rest of the items in the array.
To sort an unsorted list with 'n' number of elements, we need to make ((n-
WorstCase: O(n2)
BestCase: Ω(n2)
Average Case : Θ(n2)
Implementaion of Selection Sort Algorithm using C Programming
Language
#include<stdio.h>
#include<conio.h>
void main(){
int size,i,j,temp,list[100];
clrscr();
getch();
}
Output: