Programming Fundamentals

Similar documents
Standard File Pointers

File I/O. Arash Rafiey. November 7, 2017

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

File IO and command line input CSE 2451

IO = Input & Output 2

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

C for Engineers and Scientists: An Interpretive Approach. Chapter 14: File Processing

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Introduction to file management

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Input / Output Functions

EM108 Software Development for Engineers

Engineering program development 7. Edited by Péter Vass

File Access. FILE * fopen(const char *name, const char * mode);

CE Lecture 11

Files. Programs and data are stored on disk in structures called files Examples. a.out binary file lab1.c - text file term-paper.

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Input/Output and the Operating Systems

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

System Software Experiment 1 Lecture 7

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

C programming basics T3-1 -

Standard C Library Functions

M.CS201 Programming language

Data File and File Handling

PROGRAMMAZIONE I A.A. 2017/2018

Lecture 9: File Processing. Quazi Rahman

Organization of a file

Fundamentals of Programming. Lecture 15: C File Processing

25.2 Opening and Closing a File

CS240: Programming in C

CSI 402 Lecture 2 Working with Files (Text and Binary)

2009 S2 COMP File Operations

Chapter 12. Files (reference: Deitel s chap 11) chap8

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Input/Output: Advanced Concepts

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

fopen() fclose() fgetc() fputc() fread() fwrite()

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

C Programming Language

SAE1A Programming in C. Unit : I - V

Computer Programming: Skills & Concepts (CP) Files in C

Computer Programming Unit v

C-Refresher: Session 10 Disk IO

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

C mini reference. 5 Binary numbers 12

File (1A) Young Won Lim 11/25/16

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Pointers and File Handling

HIGH LEVEL FILE PROCESSING

Computer programming

C Basics And Concepts Input And Output

8. Characters, Strings and Files

Advanced C Programming Topics

Fundamentals of Programming & Procedural Programming

CSCI 171 Chapter Outlines

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Contents. A Review of C language. Visual C Visual C++ 6.0

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Ch 11. C File Processing (review)

CS1003: Intro to CS, Summer 2008

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Lab # 4. Files & Queues in C

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

File Handling. Reference:

File I/O. Preprocessor Macros

Chapter 10. File Processing 248 FILE PROCESSING

ENG120. Misc. Topics

Course organization. Course introduction ( Week 1)

Program Design (II): Quiz2 May 18, 2009 Part1. True/False Questions (30pts) Part2. Multiple Choice Questions (40pts)

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

C Programming 1. File Access. Goutam Biswas. Lect 29

Introduction to C Recursion, sorting algorithms, files

C PROGRAMMING. Characters and Strings File Processing Exercise

Chapter 11 File Processing

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

C File Processing: One-Page Summary

Lecture6 File Processing

File Handling. 21 July 2009 Programming and Data Structure 1

Programming. Functions and File I/O

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Programming & Data Structure

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

DS: CS Computer Sc & Engg: IIT Kharagpur 1. File Access. Goutam Biswas. ect 29

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name.

UNIX Shell. The shell sits between you and the operating system, acting as a command interpreter

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Chapter 10: File Input / Output

Transcription:

Programming Fundamentals Day 4 1

Session Plan Searching & Sorting Sorting Selection Sort Insertion Sort Bubble Sort Searching Linear Search Binary Search File Handling Functions Copyright 2004, 2 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 Copyright 2004, 3 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. 3

Bubble Sort Bubble the smallest element up in the list. 1 st pass of the Array 2 nd 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 Copyright 2004, 4 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. 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]); Copyright 2004, 5 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 n 2. 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; Copyright 2004, 6 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); Copyright 2004, 7 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 Copyright 2004, 8 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 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. Copyright 2004, 9 9

Selection Sort 9 4 1 7 8 10 ia[0] 1 ia[1] 4 ia[2] 9 ia[3] 7 ia[4] 8 ia[5] 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] Copyright 2004, 10 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] Copyright 2004, 11 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]); Copyright 2004, 12 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); Copyright 2004, 13 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 n 2. 13

Insertion Sort 12 5 20 18 Compare the first two elements of the array and swap them so that they are in place 5 12 20 18 Now take the third element and insert in place within the presorted array on 2 elements 5 12 20 18 Repeat this process till you reach the end of the array 5 12 18 20 Copyright 2004, 14 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 Copyright 2004, 15 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. 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]); Copyright 2004, 16 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); Copyright 2004, 17 17

Which Sorting algo. to use Factors that help in deciding the sorting algorithm to be used are +Memory +Performance +Flexibility +Concise code Copyright 2004, 18 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. 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 Copyright 2004, 19 Values stored in arrays often need to be queried. Searching techniques play a important role here 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 Copyright 2004, 20 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). 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 "); Copyright 2004, 21 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; Copyright 2004, 22 The array is aiarr[] is passed using pass by reference mechanism to the function 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 "); Copyright 2004, 23 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 End-If Else Low = Middle + 1 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 log 2 N comparisons to search an element in an array of size N. 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; Copyright 2004, 24 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. 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); Copyright 2004, 25 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. Copyright 2004, 26 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; Copyright 2004, 27 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 r w overwritten. a to the end of the file. Description Open a text file for reading. Create a text file for writing. If the file exists, it is Open a text file in append mode. Text is added 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. 27

Opening File fopen() - opens a file in the mode specified Prototype declaration FILE *fopen( filename mode ); Read mode Write Mode Append Mode Read Write Mode Write Read Mode Append,Read-Write Mode r w a a+ w+ a+ Opens file for reading purposes, File has to exist Opens file for writing purposes, File is recreated Opens file for writing purposes, File is not recreated if it exists Opens file for reading+writing purposes, File has to exist. Existing data can be modified, new data cannot be added Opens the file for r+w purposes. File is recreated Opens the file for read+write+append mode Copyright 2004, 28 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 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 ); Copyright 2004, 29 29

Closing File fclose() - opens a file in the mode specified Prototype declaration int fclose(file *); Copyright 2004, 30 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. 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); Copyright 2004, 31 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 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 Copyright 2004, 32 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 ) fclose( fp ); putchar( c ); c = getc ( 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. 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"); Copyright 2004, 33 Names.txt is a file already created using a text editor. Each line in the file contains a name followed by an integer age. 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); Copyright 2004, 34 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; 34

Some More Examples #include <stdio.h> #include <stdlib.h> int m ain() int num ; char buffer[20]; printf("enter a num ber: "); /* Use the fgets function to validate input */ fgets(buffer, 20, stdin); num = atoi(buffer); printf("the num ber you entered was % d\n", num ); return 0; #include <stdio.h> int m ain() FILE *in, *out; int key; if ((in = fopen("junk.txt", "r")) == NULL) puts("unable to open the file"); return 0; out = fopen("copy.txt", "w"); while (!feof(in)) key = fgetc(in); if (!feof(in)) fputc(key, out); fclose(in); fclose(out); return 0; Copyright 2004, 35 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) Copyright 2004, 36 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. Copyright 2004, 37 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. Copyright 2004, 38 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. Copyright 2004, 39 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. Copyright 2004, 40 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. Copyright 2004, 41 41

Summary Various sorting and searching methods Basic operations of opening, reading/writing and closing file Copyright 2004, 42 42

Thank You! Copyright 2004, 43 43