Вы находитесь на странице: 1из 43

Programming Fundamentals

Day 4

ER/CORP/CRS/LA06/003 1
Session Plan
• Searching & Sorting
– Sorting
• Selection Sort

• Insertion Sort

• Bubble Sort

– Searching

• Linear Search

• Binary Search

• File Handling Functions

ER/CORP/CRS/LA06/003
Copyright © 2004, 2
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 2
Sorting Techniques
•Bubble Sort
•Sorts by comparing adjacent elements and swap whenever required

•Selection Sort
•Sorts the array by selecting the first smallest element,putting it in the first position of
the array, The second smallest element is put in the second position of the array and
so on.

•Insertion Sort
•Sorts the array by inserting each element of the array in a existing presorted array of
elements

ER/CORP/CRS/LA06/003
Copyright © 2004, 3
Infosys Technologies Ltd Version no: 2.0

The sorting refers to the operation of arranging data in some given order, such as increasing
or decreasing (with numerical data) or alphabetically (with character data). There are a
number of sorting methods –Bubble sort, Selection sort, Insertion sort, Heap sort, Quick sort
etc.. The particular method one chooses depends on the properties of the data and the
operations one may perform on the data. However, we will briefly discuss only on the first
three sorting methods implemented for array sorting.

ER/CORP/CRS/LA06/003 3
Bubble Sort
Bubble the smallest element up in the list.

1st pass of the Array 2nd pass of the Array

10 23 12 5 23 12 10 5

23 10 12 5 23 12 10 5

23 12 10 5 23 12 10 5

23 12 10 5 23 12 10 5

The pass in which there is no swapping of elements indicates array is sorted

ER/CORP/CRS/LA06/003
Copyright © 2004, 4
Infosys Technologies Ltd Version no: 2.0

The sorting method followed in Bubble Sort is: Keep passing through the array, exchanging
adjacent elements that are out of order, continuing until the array is sorted. In other word,
“Bubble up” the smallest element to the last location of the array. Implementation of the
Bubble Sort is easier than the Insertion or Selection sort. But bubble sort is generally slower
than the other two methods. Its is slower because it need to scans through the entire array
and swap adjacent elements whenever required. Even the array is sorted number of passes
required is one.

ER/CORP/CRS/LA06/003 4
Bubble Sort Program
#include <stdio.h>
int iRead_Array_Of_Numbers(int []);
int iBubble_Sort(int [], int);
int iBubble(int [], int)
int main()
{
int iNumberOfElements,aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(aiArrNumbers);
iBubble_Sort(iArrNumbers, iNumberOfElements) ;
printf(”The Sorted elements are : ");
for(iIndex = 0; iIndex < iNumberOfElements; iIndex++)
printf("%d",aiArrNumbers[iIndex]);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 5
Infosys Technologies Ltd Version no: 2.0

The efficiency of the sort methods is calculated as number of moves required to sort the
array in the average case and considering only the highest order terms in the result. The
number of moves required for sorting an array using the Bubble Sort is of the order of n2.

ER/CORP/CRS/LA06/003 5
Bubble Sort Program- (Contd..)

/* Function to sort elements of an array using Bubble Sort */


int iBubble_Sort(int aiArr[], int iNoElements)
{
int iIndex, iValue;
for(iIndex = iNoElements - 1; iIndex > 0; iIndex-- )
{
iValue = iBubble(aiArr, iIndex);
if( iValue == 0)
break;
}
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 6
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 6
Bubble Sort Program-(Contd..)
int iBubble(int aiArr[], int iLast)
{
int iIndex, iSwap;
iSwap = 0;
for(iIndex = 0; iIndex < iLast; iIndex++)
if ( aiArr[iIndex] > aiArr[iIndex + 1] )
{
swap(aiArr, iIndex, iIndex + 1);
iSwap = iSwap +1;
}
return(iSwap);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 7
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 7
Selection Sort

The next smallest value must be found and placed in order.

•find the smallest element in the array


•exchange it with the element in the first position
•find the second smallest element
•exchange it with the element in the second position

ER/CORP/CRS/LA06/003
Copyright © 2004, 8
Infosys Technologies Ltd Version no: 2.0

Lets us look at sorting as follows.


First the smallest array element is identified. This is swapped with the first element of the
array
Second the next smallest element is identified and this is swapped with the second element
of the array.
This process continues till all the elements of the array are put in order.
Since the technique involves selecting the minimum element its called selection sort

ER/CORP/CRS/LA06/003 8
Selection Sort
• Algorithm :

• Find the position p, and the value a[p], of the smallest element in the unsorted
array;

• Swap the element at a[p] with the element at the first position of the unsorted
part of the array.

ER/CORP/CRS/LA06/003
Copyright © 2004, 9
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 9
Selection Sort

9 4 1 7 8 10

ia[0] ia[1] ia[2] ia[3] ia[4] ia[5]


1 4 9 7 8 10

Ia[0] Ia[1] Ia[2] Ia[3] Ia[4]

1 4 9 7 8 10

Ia[1] Ia[2] Ia[3] Ia[4]

ER/CORP/CRS/LA06/003
Copyright © 2004, 10
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 10
Selection Sort

1 4 7 9 8 10

Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[5]

1 4 7 8 9 10

Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[5]

1 4 7 8 9 10

Ia[0] Ia[1] Ia[2] Ia[3] Ia[4] Ia[5]

ER/CORP/CRS/LA06/003
Copyright © 2004, 11
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 11
Selection Sort
#include <stdio.h>
int iRead_Array_Of_Numbers(int [ ]);
void vSelection_Sort(int [ ], int);
int iMinimum_In_An_Array(int [ ], int , int);
int iSwap_Elements(int [ ], int , int);
void main( )
{ int iNumberOfElements, aiArrNumbers[10],iIndex;
iNumberOfElements = iRead_Array_Of_Numbers(aiArrNumbers);
iSelection_Sort(aiArrNumbers, iNumberOfElements) ;
printf(”The Sorted elements are : ");
for(iIndex = 0; iIndex < iNumberOfElements; iIndex++)
printf("%d", iArrNumbers[iIndex]);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 12
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 12
Selection Sort
/* Function to sort elements of an array using Selection Sort */

void vSelection_Sort(int aiArr[ ], int iNoElements)


{
int iIndex;
int iPos;
for(iIndex = 0; iIndex < iNoElements - 1; iIndex++)
{
iPos = iMinimum_In_An_Array(iArr, iIndex, iNoElements -1);
iSwap_Elements(iArr, iIndex, iPos);
}
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 13
Infosys Technologies Ltd Version no: 2.0

A disadvantage of selection sort is that the user of this method might be surprised to find
that it takes about as long to sort an already ordered array as it does for an unordered array!
The number of moves required for sorting an array using the Selection Sort is of the order of
n2.

ER/CORP/CRS/LA06/003 13
Insertion Sort

12 5 20 18 Compare the first two elements of the array and


swap them so that they are in place

Now take the third element and insert in place


5 12 20 18
within the presorted array on 2 elements

Repeat this process till you reach the end of the


5 12 20 18
array

5 12 18 20

ER/CORP/CRS/LA06/003
Copyright © 2004, 14
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 14
Insertion Sort
Insert the next element into the correct position of the ordered part and, in the
process, extend the ordered section by one element.

Algorithm :

• 1. Find the minimum and put it in place to act as


sentinel.
• 2. While there are still elements to be inserted in the
ordered part do :
• a) select next element x to be inserted
• b) while x is less than preceding element do
• b.1) move preceding element up one position,
• b.2) extend search back one element further;
• c) insert x at current position

ER/CORP/CRS/LA06/003
Copyright © 2004, 15
Infosys Technologies Ltd Version no: 2.0

Insertion sort works by considering the elements one at a time and inserting the element in
its proper place among those already considered. In other word, the (i+1) th element K[i] is
inserted into its rightful place among K[0], K[1], …, K[i - 1 ], which are previously placed in a
sorted order.

ER/CORP/CRS/LA06/003 15
Insertion Sort Program
#include <stdio.h>
int iRead_Array_Of_Numbers(int []);
int iInsertion_Sort(int [ ], int);

int main( )
{
int iNumberOfElements, aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(aiArrNumbers);
iInsertion_Sort(aiArrNumbers, iNumberOfElements) ;
printf(”The Sorted elements are : ");
for(iIndex = 0; iIndex < iNumberOfElements; iIndex++)
printf("%d", aiArrNumbers[iIndex]);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 16
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 16
Insertion Sort Program
/* Function to sort elements of an array using Insertion Sort */

int iInsertion_Sort(int aiArr[], int iNoElements)


{
int iIndex;
int iPos;
for(iIndex = 1; iIndex < iNoElements; iIndex++)
……..;
……..;

return(1);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 17
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 17
Which Sorting algo. to use

Factors that help in deciding the sorting algorithm to be used are


+Memory
+Performance
+Flexibility
+Concise code

ER/CORP/CRS/LA06/003
Copyright © 2004, 18
Infosys Technologies Ltd Version no: 2.0

While deciding upon which sorting algorithm to be used there are several things that need to
be considered. Number of comparisons and swaps have a direct impact on the performance
of the code
Bubble sort is the simplest to use and implement but here the #of comparisons and swaps
are more which results in poor performance is the array size is large.
The bubble sort algorithm has a provision to stop once array is sorted.The selection sort, on
the other hand, always needs to go through the same amount of work regardless of the data
The insertion sort is a little better and whilst it cannot detect that it has finished sorting, the
logic of the algorithm means that it comes to a rapid conclusion when dealing with sorted
data.

ER/CORP/CRS/LA06/003 18
Searching
• Heavily used in production programming

• Efficiency is a must

• Lot of techniques available that work on sorted or unsorted arrays. Some of the
techniques are
– Linear Search
– Binary Search

ER/CORP/CRS/LA06/003
Copyright © 2004, 19
Infosys Technologies Ltd Version no: 2.0

Values stored in arrays often need to be queried. Searching techniques play a important
role here

ER/CORP/CRS/LA06/003 19
Linear Search
12 5 23 35

Compare the search value with each


and every element of the array till a match
is found
Stop comparison once match is found or
you reach the end of the array

Search value - 5
5 is compared with 10 and then 5 since the match is found no further
comparisons carried out

Search value - 10
10 is compared with 12,5,23,35. But no match is found. However the end of
array has reached without a match so no further comparisons

ER/CORP/CRS/LA06/003
Copyright © 2004, 20
Infosys Technologies Ltd Version no: 2.0

Consider a array of 4 values. In Linear Search, as the number of elements increases, the
time taken to perform the search increases linearly. The linear search requires n
comparisons in the worst case (i.e., when the elements of the array are in the reverse order
of sorting).

ER/CORP/CRS/LA06/003 20
Linear Search
# include <stdio.h>
int iRead_Array_Of_Numbers(int []);
int iLinear_Search(int [ ], int, intt);
int main( )
{
int iPos, iNumberOfElements, iElementToBeSearched, aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(iArrNumbers);
printf (“Enter the element to be searched for : “);
scanf(“%d”, &iElementToBeSearched);
iPos = iLinear_search (aiArrNumbers, iNumberOfElements, iElementToBeSearched) ;
if (iPosOfElement >= 0) { printf("Element is present at %d", iPos); }
else { printf("Element is not present ");}
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 21
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 21
Linear Search
/* Function to search for an element in an array using Linear Search */
int iLinear_search(int aiArr[], int iNoElements, int iNumberToBeSearched)
{
int iFound, iIndex, iFound = 0;
for(iIndex = 0; iIndex < n; iIndex ++ )
if (aiArr[iIndex] == iNumberToBeSearched)
{
iFound =1;
break;
}
if (iFound == 0)
return -1;
else
return iIndex;
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 22
Infosys Technologies Ltd Version no: 2.0

The array is aiArr[] is passed using pass by reference mechanism to the function

ER/CORP/CRS/LA06/003 22
Binary Search
#include <stdio.h>
int iRead_Array_Of_Numbers(int aiArr[ ]);
int iBinary_Search(int aiArr[ ], int iNoElements, int iSearchElement);
int main()
{
int iPosOfElement, iNumberOfElements,iElementToBeSearched,aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(iArrNumbers);
printf (“Enter the element to be searched for : “);
scanf(“%d”, &iElementToBeSearched);
iPosOfElement = iBinary_Search(iArrNumbers,
iNumberOfElements,iElementToBeSearched) ;
if (iPosOfElement >= 0)
printf("Element is present at %d", iPosOfElement);
else
printf("Element is not present ");
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 23
Infosys Technologies Ltd Version no: 2.0

Binary search works by comparing your search element with the center element of the array. Depending on whether the search element
is greater or less than the middle element we now consider second half or the first half of the array and repeat the procedure
The Binary search algorithm is given below.
Arr is an ordered Array of N elements. skey is the key element to be searched for. Low, Middle and High denote the lower, middle and
upper limits of the search interval, respectively.
Algorithm
Start
Step 1 : Low = 1
Step 2 : High = N -1
Step 3 : Repeat Step 4 to Step 5 While Low <= High
Step 4 : Middle = (Low + High) / 2
Step 5 : If ( Arr[Middle] = skey) Then
WRITE “successful search”
Stop
Else If ( skey < Arr[Middle] ) Then High = Middle - 1
Else Low = Middle + 1
End-If
End-If
Step 6 : WRITE “unsuccessful search”
End
Since the searching algorithm works by continuously dividing your array into two parts, in the worst case binary search will require log2
N comparisons to search an element in an array of size N.

ER/CORP/CRS/LA06/003 23
Binary Search
/* Function to search for an element in an array using binary search */
int iBinary_Search(int aiArr[], int iNoElements,
int iNumberToBeSearched)
{
int iLowPos, iHighPos, iMidPos,iLowPos = 0;
iHighPos = iNoElements -1;
while (iHighPos >= iLowPos) {
iMidPos = (iLowPos + iHighPos)/2;
if (iArr[iMidPos] == iNumberToBeSearched)
return iMidPos;
else
if (iArr[iMidPos] < iNumberToBeSearched)
iLowPos = iMidPos + 1;
else
iHighPos = iMidPos -1;
}
return -1;
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 24
Infosys Technologies Ltd Version no: 2.0

In the array implementation of Linear Search, we can improve significantly the search time if
the array is already ordered by using a search method known as Binary Search.

ER/CORP/CRS/LA06/003 24
/*Read the data into the array*/
int iRead_Array_Of_Numbers(int aiArr[ ]){
int iNumber;
iNumber =0;
Choice = ‘y’;
while(Choice == ‘Y’ || Choice == ‘y’)
{
printf(“\n Enter the %d element “, iNumber + 1);
fflush(stdin);
scanf(“%d”, &aiArr[iNumber - 1]);
iNumber = iNumber + 1;
printf(“\nDo you want to continue: enter (y/n)”);
fflush(stdin);
scanf(“%c”,&Choice);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 25
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 25
I/O Streams in C

• File handling in C is provided by a number of functions in the standard


library.
• All input/output is based on the concept of a stream.
• There are two types of stream:
– text stream
– binary stream

• A text stream is a sequence of characters composed into lines, each line is


terminated with a newline (\n) character.
• A binary stream is a sequence of unprocessed bytes - newline has no
significance.

ER/CORP/CRS/LA06/003
Copyright © 2004, 26
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 26
File Handling Functions in C
Basic operations to be carried out on files
1. Opening of file
2. Closing of file
3. Reading file
4. Writing file
5. Traversing the pointer
6. Checking for end of file
7. Get the current position in file

For all the file handling operations the pointer to file is created which is of the
data type :-
FILE pointer – data type defined in stdio.h
Eg. FILE *fp;

ER/CORP/CRS/LA06/003
Copyright © 2004, 27
Infosys Technologies Ltd Version no: 2.0

File access in C is achieved by associating a stream with a file.


FILE *in; The fopen function is used to open the file. Files may be opened in a number of modes, as shown in the
following table.
File Modes Operator Description
r Open a text file for reading.
w Create a text file for writing. If the file exists, it is
overwritten.
a Open a text file in append mode. Text is added
to the end of the file.
r+ Open a text file for reading and writing.
w+ Create a text file for reading and writing. If the
file exists, it is overwritten.
a+ - Open a text file for reading and writing at the
end.
The update modes are used with fseek, fsetpos and rewind functions. The fopen function returns a file pointer, or
NULL if an error occurs. The following example opens a file called junk.txt in read-only mode. It is good
programming practice to test the file exists.
if ((in = fopen("junk.txt", "r")) == NULL) { puts("Unable to open the file"); return 0; }
Files are closed using the fclose function. fclose(in);
The feof function is used to test for the end of the file. The functions fgetc, fscanf, and fgets are used to read data
from the file. The following example lists the contents of a file on the screen, using fgetc to read the file a character
at a time.

ER/CORP/CRS/LA06/003 27
Opening File
fopen() - opens a file in the mode specified
Prototype declaration – FILE *fopen(“filename” “mode”);

Read mode r Opens file for reading purposes, File has to


exist
Write Mode w Opens file for writing purposes, File is
recreated
Append Mode a Opens file for writing purposes, File is not
recreated if it exists
Read Write Mode a+ Opens file for reading+writing purposes,
File has to exist. Existing data can be
modified, new data cannot be added
Write Read Mode w+ Opens the file for r+w purposes. File is
recreated
Append,Read-Write Mode a+ Opens the file for read+write+append mode

ER/CORP/CRS/LA06/003
Copyright © 2004, 28
Infosys Technologies Ltd Version no: 2.0

Your program must open a file before it can access it. This is done using the fopen function,
which returns the required file pointer. If the file cannot be opened for any reason then the
value NULL will be returned.
You will usually use fopen as follows
if ((output_file = fopen("output_file", "w")) == NULL) fprintf(stderr, "Cannot open %s\n",
"output_file");fopen takes two arguments, both are strings, the first is the name of the file to
be opened, the second is an access character, which is usually one from the above table

ER/CORP/CRS/LA06/003 28
Examples of fopen calls

FILE *fp1, *fp2, *fp3;


char filename[32];

/*open existing file for reading*/


fp1=fopen(“mydatafile”, “r”);

/*open to write - if file exists it is overwritten */


fp2=fopen(“results”,”w”);

printf(“Name of output file:”);


scanf(“%s”, filename);
/*append to existing file or create new file */
fp3=fopen(filename,”a”);

ER/CORP/CRS/LA06/003
Copyright © 2004, 29
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 29
Closing File
fclose() - opens a file in the mode specified
Prototype declaration – int fclose(FILE *);

ER/CORP/CRS/LA06/003
Copyright © 2004, 30
Infosys Technologies Ltd Version no: 2.0

The fclose command can be used to disconnect a file pointer from a file. This is usually done
so that the pointer can be used to access a different file. Systems have a limit on the number
of files which can be open simultaneously, so it is a good idea to close a file when you have
finished using it.
This would be done using a statement like
fclose(output_file); If files are still open when a program exits, the system will close them for
you. However it is usually better to close the files properly.
The function fclose is used to close the file i.e. indicate that we are finished processing this
file.
We could reuse the file pointer fp by opening another file. Always remember to close a file
before reopening the file in any other mode.

ER/CORP/CRS/LA06/003 30
Formatted Input/Output
 The functions fscanf and fprintf provide the equivalent for any open file.
 Their prototypes:
int fscanf(FILE *fp, char *format, arg1, arg2, ...);
int fprintf(FILE *fp, char *format, arg1, arg2, ...);

For Exmaple

• input an integer and a float from file *fp1


fscanf(fp1,”%d%f”, &x, &y);
• output to file * fp2
fprintf(fp2, ”Final total was %d”, total);

ER/CORP/CRS/LA06/003
Copyright © 2004, 31
Infosys Technologies Ltd Version no: 2.0

The fscanf and fprintf function work in a similar manner as scanf and printf.

Arguments to fscanf are in addition to the format stirng and the variable list , pointer to the
file from which read operation needs to be done.
Arguments to printf are in addition to the format stirng and the variable list , pointer to the file
on which write operation needs to be done.

Some more file I/O functions


•fgets
•fputs
•fgetc
•fputc

ER/CORP/CRS/LA06/003 31
Character / String Input
char *fgets (char *s, int n, FILE *fp);
char *gets(char *s);
• fgets reads characters into the array s, from file * fp until a newline or n-1
characters have been read
– It returns NULL if an error or EOF occurs.
• fgets retains any newline characters
– gets does not
• make sure the character array s is large enough to hold all the data being
read!

• fgets is quite useful when you don't know how many lines a file contains
• keep reading line-by-line it returns NULL
• then use sscanf(char * s, char *format, arg1, arg2, ...)
to break a string s into parts
sscanf(line, "%s %d", name, &age);
• breaks line into a string variable name and integer variable age

ER/CORP/CRS/LA06/003
Copyright © 2004, 32
Infosys Technologies Ltd Version no: 2.0

The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).
Thus the statement “ c = getc(fp); “ reads the next character from the file referenced by fp and
the statement “putc(c,fp); “ writes the character c into file referenced by fp

/* file.c: Display contents of a file on screen */


#include <stdio.h>
void main()
{
FILE *fp; int c ;
fp = fopen( “prog.c”, “r” );
c = getc( fp ) ;
while ( c != EOF )
{
putchar( c ); c = getc ( fp );
}
fclose( fp );
}
In this program, we open the file prog.c for reading. We then read a character from the file. This file must exist
for this program to work. If the file is empty, we are at the end, so getc returns EOF a special value to indicate
that the end of file has been reached. (Normally -1 is used for EOF).The while loop simply keeps reading
characters from the file and displaying them, until the end of the file is reached.

ER/CORP/CRS/LA06/003 32
File input example
char line[50], name[30];
int age;
FILE * fp;
fp = fopen("Names.txt", "r");
if (fp != NULL) {
while (fgets(line, 49, fp) != NULL) {
sscanf(line, "%s %d", name, &age);
printf("Name is %s, age is %d\n", name, age);
}
printf("End of file");
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 33
Infosys Technologies Ltd Version no: 2.0

Names.txt is a file already created using a text editor. Each line in the file contains a name
followed by an integer age.

ER/CORP/CRS/LA06/003 33
Simple Example Code
#include <stdio.h>
main () {
FILE *fp1,*fp2,*fp3;
char filename[32];
char result[30]="";
int letter;
fp1 = fopen("mydata.txt","r");
fp2 = fopen("results.txt","w");
printf("Name of output file: ");
scanf("%s",filename);
fp3= fopen(filename,"a");
fgets(result, 12, fp1);
printf("The first file contains: %s", result);
fputs(result,fp2);
letter='a';
fputc(letter,fp3);
fclose(fp1);fclose(fp2);fclose(fp3);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 34
Infosys Technologies Ltd Version no: 2.0

Some more examples


#include <stdio.h>
int main()
{
FILE *in; int key;
if ((in = fopen("junk.txt", "r")) == NULL)
{
puts("Unable to open the file"); return 0;
}
while (!feof(in))
{
key = fgetc(in); /* The last character read is the end of file marker */ /* so don't print it */
if (!feof(in)) putchar(key);
}
fclose(in);
return 0;
}

ER/CORP/CRS/LA06/003 34
Some More Examples
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> int m ain()
int m ain() {
{ F ILE *in, *out; int key;
int num ; char buffer[20]; if ((in = fopen("junk.txt", "r"))
printf("E nter a num ber: "); /* == N U LL)
U se the fgets function to {
validate input */ puts("U nable to open the
fgets(buffer, 20, stdin); file"); return 0;
num = atoi(buffer); }
printf("T he num ber you out = fopen("copy.txt", "w");
entered was % d\n", num ); while (!feof(in))
return 0; {
} key = fgetc(in);
if (!feof(in)) fputc(key, out);
}
fclose(in);
fclose(out);
return 0;
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 35
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 35
File Functions : Used in Project
• int fiOpenFile(int iFile)

• int fiReadFile (char acLine[ ], int iFile, int ipos)

• void fvWriteFile (char acLine[ ], int iFile)

• int fiUpdateFile (char acLine[ ], int iFile)

• int fiCloseFile (int iFile)

ER/CORP/CRS/LA06/003
Copyright © 2004, 36
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 36
File open: fiOpenFile

• Prototype : int fiOpenFile(int iFile)


– Parameters :
– iFile- integer :-
» DEP_FILE to open dept.txt,
» EMP_FILE to open emp.txt.
– e.g., int fiOpenFile(DEP_FILE)
– Return value: The function returns 1 on success and 0 on
failure.
– Remarks :
• The function opens the file as specified in the iFile argument.
This function should be used only once at the beginning of the
program.

ER/CORP/CRS/LA06/003
Copyright © 2004, 37
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 37
Read file : fiReadFile
• Prototype : int fiReadFile ( char acLine[ ],
int iFile, int ipos)
– Parameters :
– acLine - A string: The string that is read from the file.
– iFile - integer :
» DEP_FILE to read dept.txt
» EMP_FILE to read emp.txt
– ipos - integer :
» BEGIN to read from the beginning.
» CURRENT to read from the current position.
– Return value: The function returns 1 on success and 0 on
failure.
– Remarks :
– The function reads a line into acLine from the file that
specified by iFile argument.
– If ipos is BEGIN it reads from the first line.
– If ipos is CURRENT it reads the line from current-position.

ER/CORP/CRS/LA06/003
Copyright © 2004, 38
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 38
Write file : fvWriteFile

• Prototype: void fvWriteFile (char acLine[ ],


int iFile)
– Parameters :
• acLine - A string:
– The string that is written into the file.
• iFile - integer :
– DEP_FILE to open dept.txt,
– EMP_FILE to open emp.txt.
– Return value: none.
– Remarks :
– The function writes a line as in argument acLine into the
file that specified by iFile argument.

ER/CORP/CRS/LA06/003
Copyright © 2004, 39
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 39
Update file : fiUpdateFile
• Prototype: int fiUpdateFile (char acLine[ ],
int iFile)
– Parameters :
• acLine - A string:
– The string that is written into the file.
• iFile - integer :
– DEP_FILE to open dept.txttxt,
– EMP_FILE to open emp.txt.
– Return value: The function returns 1 on success and 0 on
failure.
– Remarks :
• The function updates a line in the file as specified by iFile
argument. The string as in argument sLine will replace the line.
It will be the line, which is last read from the file by fiReadFile
function.

ER/CORP/CRS/LA06/003
Copyright © 2004, 40
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 40
Close file: fiCloseFile

• Prototype: int fiCloseFile (int iFile)

• Parameters :
• iFile - integer :
– DEP_FILE to open dept.txt,
– EMP_FILE to open emp.txt.
– Return value: The function returns 1 on success and 0 on failure.
– Remarks: The function closes the file.

ER/CORP/CRS/LA06/003
Copyright © 2004, 41
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 41
Summary
• Various sorting and searching methods

• Basic operations of opening, reading/writing and closing file

ER/CORP/CRS/LA06/003
Copyright © 2004, 42
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 42
Thank You!

ER/CORP/CRS/LA06/003
Copyright © 2004, 43
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 43

Вам также может понравиться